Product of Array Except Self
On this page
Problem statement
Given an integer array
nums, return an arrayoutwhereout[i]is the product of every element exceptnums[i]. Do it in O(n) time without using division. Follow-up: use O(1) extra space, not counting the output array. You may assume every such product fits in a 32-bit integer.
A short array problem that teaches prefix and suffix accumulation, the same idea behind prefix sums, but with multiplication. The "no division" rule exists because division fails as soon as the array contains a zero. Original problem: LeetCode 238.
Example
![Each output is the product of the other three numbers: out[1] = 2 · 4 · 5 = 40.](https://storage.ghost.io/c/cc/3d/cc3dd2ec-1125-4515-87dd-11389c0d3c50/content/images/2026/11/000-41d590d3-3.png)
Input: [2, 3, 4, 5]
Output: [60, 40, 30, 24]
Input: [3, 0, 2, 4]
Output: [0, 24, 0, 0] # only out[1] skips the zero
Constraints (assumed)
- 2 ≤ n ≤ 10⁵; −30 ≤ nums[i] ≤ 30.
- Every product of all-but-one element fits in 32 bits.
What this question tests
- Splitting "everything except i" into everything left of i times everything right of i.
- Two passes, and reusing the output array as working space to reach O(1) extra memory.
- Handling zeros and negatives without special cases.
Questions to ask first
- Is division allowed? (Here: no. Even if it were, zeros need careful handling.)
- Can there be zeros or negative numbers? (Here: yes, both.)
- Does the output array count as extra space? (Here: no.)
- Can the products overflow? (Here: assume they fit; otherwise use 64-bit or big integers.)
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.