mediumArrays & HashingAmazonMetaApple
Relay Baton Totals
Each runner on a relay team is awarded the product of their teammates' leg scores — never their own. Compute every runner's score.
Given an integer array `legs`, return an array `out` where `out[i]` equals the product of every value in `legs` other than `legs[i]`. Solve it in O(n) time without using the division operator.
Choose approach
1
02
13
24
3Mapout
0→1
1→1
2→1
3→1
1/10
Narrationstep 1 of 10
Each runner i wants the product of all other legs. Two sweeps — left prefix, then right suffix — multiplied into one output.
Variables
phase=init
left=1
right=1
How to think about it
- The product of all others = (product of everything on the left of i) × (product of everything on the right of i).
- Compute those two products with two sweeps.
- Reuse the output array: store left prefix in pass 1, multiply the right suffix in pass 2.
- No division — important when legs contains zero.
Edge cases to catch in interview
- Exactly one zero → every other out[i] is 0; that single zero slot gets the non-zero product.
- Two or more zeros → entire out is zero.
- Negatives — the sign flips naturally.
- Length-2 array — out[0] = legs[1], out[1] = legs[0].
Examples
Example 1
[24,12,8,6]{"legs":[1,2,3,4],"values":[1,2,3,4]}
Example 2
[0,0,9,0,0]{"legs":[-1,1,0,-3,3],"values":[-1,1,0,-3,3]}
Any zero in legs forces most outputs to 0.
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed