Full answer
Problem
Given nums, return answer where answer[i] is the product of all elements except nums[i]. Do not use division.
Example: [1, 2, 3, 4] gives [24, 12, 8, 6].
Constraints: 2 <= len(nums) <= 10^5, values from -30 to 30, the products fit in a 32-bit integer. Target O(n) time.
Brute force
For each i, multiply all other elements: O(n^2).
The division trick (total product divided by nums[i]) is O(n) but fails when a value is 0, and the problem forbids it anyway.
Optimal approach
answer[i] = (product of nums[0..i-1]) x (product of nums[i+1..n-1]).
- Forward pass:
leftstarts at 1. Setanswer[i] = left, thenleft *= nums[i]. - Backward pass:
rightstarts at 1. Doanswer[i] *= right, thenright *= nums[i].
Why it works
After the forward pass, answer[i] is the prefix product before i. The backward pass multiplies in the suffix product after i. Because each pass multiplies by nums[i] only after using the running value, position i never includes itself.
Example with [1, 2, 3, 4]: after the forward pass answer = [1, 1, 2, 6]; the backward pass multiplies by suffix products [24, 12, 4, 1], giving [24, 12, 8, 6].
Complexity
O(n) time. O(1) extra space if the output list does not count (the usual convention); otherwise O(n).
Code
def product_except_self(nums):
"""answer[i] = product of all nums except nums[i], without division, O(n)."""
n = len(nums)
answer = [1] * n
left = 1
for i in range(n): # answer[i] = product of nums[:i]
answer[i] = left
left *= nums[i]
right = 1
for i in range(n - 1, -1, -1): # multiply by product of nums[i+1:]
answer[i] *= right
right *= nums[i]
return answer
if __name__ == "__main__":
assert product_except_self([1, 2, 3, 4]) == [24, 12, 8, 6]
assert product_except_self([-1, 1, 0, -3, 3]) == [0, 0, 9, 0, 0]
assert product_except_self([0, 0]) == [0, 0]
assert product_except_self([5, 2]) == [2, 5]
print("all tests passed")Save as a11_product_except_self.py and run python3 a11_product_except_self.py. It prints all tests passed (Python 3.13.5).
Edge cases
One zero: every position except the zero's becomes 0, and the zero's position holds the product of the rest. Two or more zeros: everything is 0. Negative numbers. Two elements (each gets the other).
Pattern
Prefix and suffix accumulation: compute "everything before" and "everything after" each index in two sweeps. The same idea solves trapping rain water (prefix and suffix maxima) and candy distribution.
def product_except_self(nums):
"""answer[i] = product of all nums except nums[i], without division, O(n)."""
n = len(nums)
answer = [1] * n
left = 1
for i in range(n): # answer[i] = product of nums[:i]
answer[i] = left
left *= nums[i]
right = 1
for i in range(n - 1, -1, -1): # multiply by product of nums[i+1:]
answer[i] *= right
right *= nums[i]
return answer
if __name__ == "__main__":
assert product_except_self([1, 2, 3, 4]) == [24, 12, 8, 6]
assert product_except_self([-1, 1, 0, -3, 3]) == [0, 0, 9, 0, 0]
assert product_except_self([0, 0]) == [0, 0]
assert product_except_self([5, 2]) == [2, 5]
print("all tests passed")Two passes with running left and right products, no division.
Complexity
Time: O(n). Space: O(1) extra besides the output list. If the output list counts as space, it is O(n).
By level
Fresher: Builds separate prefix and suffix product lists and combines them, explaining each on a small example. Should explain why division is not allowed or not safe with zeros.
Mid: Reduces to one output array and one running variable, handles zeros and explains the space convention. Tests inputs with one zero and with two zeros.
Senior: Discusses overflow in fixed-width types, log-sum tricks and their precision issues, and parallel prefix computation for very large arrays. Can explain the prefix and suffix idea as two passes of running products.
Key points
- answer[i] = prefix product before i times suffix product after i
- Fill prefix products forward, multiply suffix products backward
- Use the running value before multiplying in nums[i]
- Works with zeros, unlike division
- O(1) extra space besides output
Common mistakes
- Using division and failing on zeros
- Including nums[i] in its own product
- Allocating separate prefix and suffix arrays when one running variable suffices
- Forgetting negative numbers in reasoning about signs
Follow-ups
- How would you handle the case where division is allowed but zeros appear?
- What if the product can overflow?
- How does this idea solve trapping rain water?
Tips
- Write the prefix times suffix identity first
- Show the two passes on a four-element example
- Mention the zero problem with division
Evaluation rubric
- Correct two-pass algorithm without division
- Handles zeros
- States space convention
- Explains with an example