The Runtime Theory
mediumleetcode#prefix-sum#array

Product of Array Except Self

Build the product of all array elements except the current one without division, using prefix and suffix products in two linear passes.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

in[1,2,3,4]

out[24,12,8,6]

in[-1,1,0,-3,3]

out[0,0,9,0,0]

The machine must return an array where answer[i] is the product of everything except nums[i], and the division operator is banned. The insight: the product excluding index i factors cleanly into "product of everything to the left" times "product of everything to the right". Two passes build those prefixes and suffixes — one output array holds the left products first, then a backward pass multiplies in the running right product.

python
def product_except_self(nums):
    n = len(nums)
    ans = [1] * n
    for i in range(1, n):
        ans[i] = ans[i - 1] * nums[i - 1]
    right = 1
    for i in range(n - 1, -1, -1):
        ans[i] *= right
        right *= nums[i]
    return ans

Steps: (1) forward pass fills ans[i] with the prefix product, (2) backward pass multiplies each element by the running suffix product.

Time is O(n), two passes. Space is O(1) beyond the output array, which LeetCode does not count.

Trickiest edge case: zeros. With one zero, every position except the zero's own is 0 — the prefix/suffix approach handles this naturally, no branching needed. With two or more zeros, the entire answer is zeros. There is no division, so zeros never blow up the math.

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.