CodeArchon

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
0
2
1
3
2
4
3
Mapout
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.

1def teammate_products(legs: list[int]) -> list[int]:
2 n = len(legs)
3 out = [1] * n
4 left = 1
5 for i in range(n):
6 out[i] = left
7 left *= legs[i]
8 right = 1
9 for i in range(n - 1, -1, -1):
10 out[i] *= right
11 right *= legs[i]
12 return out
Variables
phase=init
left=1
right=1

How to think about it

  1. The product of all others = (product of everything on the left of i) × (product of everything on the right of i).
  2. Compute those two products with two sweeps.
  3. Reuse the output array: store left prefix in pass 1, multiply the right suffix in pass 2.
  4. 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