Each shelf's product of all the other shelves

Arrays, strings and hash maps Mid-level Python 3.13+ Reviewed By Best Latest Apps

Spot the bug

This version gives wrong answers. Which line is wrong?

  1. def others(m: list[int]) -> list[int]:
  2. out = [1] * len(m)
  3. run = 1
  4. for i in range(len(m)):
  5. run *= m[i]
  6. out[i] = run
  7. return out
  8. print(others([2, 3, 4]))

Choose an answer, then open Show answer below to check it.

Show answer
  • Answer: line 5 run *= m[i]

Line 5 multiplies m[i] in before storing it, so slot i includes its own value. Store run first, then multiply.

30-second answer

Make two passes. Left to right, write the product of everything before i; right to left, multiply in the product of everything after i, carried in one variable. Each slot ends as before × after. O(n) time and O(1) extra space besides the output, and zeros need no special case because nothing is divided.

Practise saying it · 45 s. No recording, just a timer

Describe the two-pass method and why it needs no division.

Say your answer out loud, then check which of these points you covered:

  • Before and after products
  • Output reused as storage
  • Zeros handled naturally

Deep dive

Division fails on zeros and hides precision issues with floats, which is why the question forbids it.

The output list doubles as the 'before' array, so only one running variable is needed for 'after'.

Two zeros make every slot zero; one zero makes every slot but its own zero. The two-pass method handles both without branching.

Python solution Ran on Python 3.13.5 · mypy --strict
Python 3.13
def others_product(mult: list[int]) -> list[int]:
    out = [1] * len(mult)
    before = 1
    for i in range(len(mult)):
        out[i] = before
        before *= mult[i]
    after = 1
    for i in range(len(mult) - 1, -1, -1):
        out[i] *= after
        after *= mult[i]
    return out

Common mistakes

  • Using division and then patching zero cases with special branches.
  • Off-by-one: including the element itself in its own 'before' or 'after' product.

Senior take & follow-ups

Say 'before times after' first and draw it on three cells. The code then reads as a direct translation.

Follow-up questions

Think of your answer first, then open the hint.

  1. How would you handle overflow in a fixed-width language?

    Show hint

    Use 64-bit integers or a modulus if the question allows; Python ints do not overflow.

  2. Can you do it in one pass?

    Show hint

    Fill from both ends at once with two running products; the total work is the same.

What each operation costs: Arrays · Dynamic Arrays · Hash Table · Hash Functions

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.