2026-09-18 — Product of Array Except Self
Difficulty: 🟡 Medium Pattern: Prefix and suffix products Time-box: 20 minutes
Problem
Given an integer array nums, return an array answer where answer[i] is the
product of every element of nums except nums[i].
Examples
[1, 2, 3, 4] -> [24, 12, 8, 6]
[-1, 1, 0, -3, 3] -> [0, 0, 9, 0, 0]
[2, 3] -> [3, 2]
Constraints
- You may not use division. (Which rules out "product of everything ÷ nums[i]" — and that restriction exists for a reason: see the hint.)
- Run in O(n).
- The output array does not count toward extra space.
Hint (open only if stuck after 10 minutes)
The division approach fails on zeroes: with one zero, every other answer is 0 and you would be dividing by zero to get the one non-zero entry. With two zeroes, everything is 0. Handling that with special cases is possible but ugly — and the interviewer's real question is whether you see the alternative.
The product of everything except i is:
(everything to the LEFT of i) × (everything to the RIGHT of i)
Both of those can be built in a single pass each.
Solution
def product_except_self(nums: list[int]) -> list[int]:
n = len(nums)
answer = [1] * n
# Pass 1: answer[i] = product of everything LEFT of i.
running = 1
for i in range(n):
answer[i] = running
running *= nums[i]
# Pass 2: multiply in the product of everything RIGHT of i.
running = 1
for i in range(n - 1, -1, -1):
answer[i] *= running
running *= nums[i]
return answer
Tracing [1, 2, 3, 4]:
| i | left product | right product | answer |
|---|---|---|---|
| 0 | 1 | 2·3·4 = 24 | 24 |
| 1 | 1 | 3·4 = 12 | 12 |
| 2 | 1·2 = 2 | 4 | 8 |
| 3 | 1·2·3 = 6 | 1 | 6 |
How it works. The first pass writes the left product into answer[i] before
folding nums[i] into the running product, so nums[i] itself is never
included. The second pass does the same from the right, multiplying into what is
already there. No division, and zeroes need no special handling at all — a zero
simply propagates into the running product like any other value.
Complexity. Time: O(n) — two passes. Space: O(1) extra — the running variables; the output array is required by the problem and does not count.
Edge cases that matter. - One zero — every position except that one gets 0; the zero's own position gets the product of the rest. Falls out automatically. - Two or more zeroes — everything is 0. Also automatic. - Two elements, the minimum interesting size. - Negative numbers — signs take care of themselves.
Common wrong answer. total = math.prod(nums) then total // nums[i]. It
is O(n) and looks clever, but it is explicitly disallowed, it crashes on a zero,
and with two zeroes there is no total to divide anyway.
Found a mistake? Edit this page on GitHub.