Product of Array Except Self
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given an integer array nums, return an array answer where answer[i] is the product of every element except nums[i].
Do it in O(n) time, and without using division.
Understand the problem
- The product of some numbers means multiplying them together: the product of
2, 3, 4is2 × 3 × 4 = 24. - For every position
i, cover upnums[i]with your finger and multiply everything else. That result goes inanswer[i]. - O(n) means you can only walk through the array a fixed number of times (once, twice...), not once per element.
- No division rules out the shortcut "multiply everything, then divide by
nums[i]".
Example 1
Input: nums = [1, 2, 3, 4]
Output: [24, 12, 8, 6]i | Cover up | Multiply the rest | answer[i] |
|---|---|---|---|
| 0 | 1 | 2 × 3 × 4 | 24 |
| 1 | 2 | 1 × 3 × 4 | 12 |
| 2 | 3 | 1 × 2 × 4 | 8 |
| 3 | 4 | 1 × 2 × 3 | 6 |
Example 2
Input: nums = [-1, 1, 0, -3, 3]
Output: [0, 0, 9, 0, 0]Every product that includes the 0 is 0. Only answer[2] skips the zero: -1 × 1 × -3 × 3 = 9.
Constraints
2 <= nums.length <= 10^5-30 <= nums[i] <= 30- Every product fits in a 32-bit integer.
Note
Follow-up: can you use only O(1) extra space? The output array doesn't count.
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
For each position, multiply "everything to my left" by "everything to my right", building both with running products in two passes.
The naive approach (and why it's slow, or not allowed)
- Recompute for every position: for each
i, loop over the whole array and multiply everything exceptnums[i]. That'snloops ofnsteps each, O(n²). - Divide: multiply everything once (
24for[1, 2, 3, 4]), thenanswer[i] = 24 / nums[i]. Fast, but the problem forbids division, and it also breaks when the array contains a0(you can't divide by zero).
The key insight
"Everything except nums[i]" splits into two parts:
nums = [1, 2, 3, 4]
↑ i = 2
left of i = 1 × 2 = 2
right of i = 4
answer[2] = 2 × 4 = 8- The product of everything before
iis called a prefix product ("prefix" = the beginning part). - The product of everything after
iis a suffix product ("suffix" = the ending part).
The trick is that you don't recompute these from scratch. Walking left to right, the prefix product for position i + 1 is just the prefix for i, times nums[i]. One multiplication per step.
Step by step
nums = [1, 2, 3, 4]. Start with answer = [1, 1, 1, 1].
Pass 1, left to right. prefix starts at 1 (there's nothing to the left of position 0).
i | answer[i] = prefix | then prefix *= nums[i] |
|---|---|---|
| 0 | 1 | 1 × 1 = 1 |
| 1 | 1 | 1 × 2 = 2 |
| 2 | 2 | 2 × 3 = 6 |
| 3 | 6 | 6 × 4 = 24 |
Now answer = [1, 1, 2, 6]: each slot holds the product of everything to its left.
Pass 2, right to left. suffix starts at 1 (nothing to the right of the last position).
i | answer[i] *= suffix | then suffix *= nums[i] |
|---|---|---|
| 3 | 6 × 1 = 6 | 1 × 4 = 4 |
| 2 | 2 × 4 = 8 | 4 × 3 = 12 |
| 1 | 1 × 12 = 12 | 12 × 2 = 24 |
| 0 | 1 × 24 = 24 | 24 × 1 = 24 |
Final answer = [24, 12, 8, 6] ✅
Notice the order inside each step: first use the running product, then multiply nums[i] into it. That's what keeps nums[i] itself out of answer[i].
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(n). Two passes over the array, one multiplication per step.
- Memory: O(1) extra. Besides the output array (which doesn't count), we only keep two numbers:
prefixandsuffix.
Common mistakes
- Multiplying before writing. If you do
prefix *= nums[i]beforeanswer[i] = prefix, every answer includes its own number. - Starting the running products at
0. Anything times0is0. The "empty product" is1. - Using two extra arrays. Separate
prefix[]andsuffix[]arrays work and are a fine first step, but the follow-up asks for O(1) extra space, which the in-place version gives you.
Going deeper
The same "running total from the left" idea is called a prefix sum when you add instead of multiply. Prefix sums answer "what's the sum of nums[a..b]?" instantly, and they show up in many interview problems.
Reference solution
/**
* @param {number[]} nums
* @return {number[]}
*/
export default function productExceptSelf(nums) {
const answer = new Array(nums.length).fill(1)
// Pass 1 (left to right): answer[i] = product of everything LEFT of i.
let prefix = 1 // nothing to the left of index 0, and the empty product is 1
for (let i = 0; i < nums.length; i++) {
answer[i] = prefix // use it first...
prefix *= nums[i] // ...then include nums[i] for the next position
}
// Pass 2 (right to left): multiply in the product of everything RIGHT of i.
let suffix = 1 // nothing to the right of the last index
for (let i = nums.length - 1; i >= 0; i--) {
answer[i] *= suffix
suffix *= nums[i]
}
return answer
}export default function productExceptSelf(nums: number[]): number[] {
const answer = new Array<number>(nums.length).fill(1)
// Pass 1 (left to right): answer[i] = product of everything LEFT of i.
let prefix = 1 // nothing to the left of index 0, and the empty product is 1
for (let i = 0; i < nums.length; i++) {
answer[i] = prefix // use it first...
prefix *= nums[i] // ...then include nums[i] for the next position
}
// Pass 2 (right to left): multiply in the product of everything RIGHT of i.
let suffix = 1 // nothing to the right of the last index
for (let i = nums.length - 1; i >= 0; i--) {
answer[i] *= suffix
suffix *= nums[i]
}
return answer
}def product_except_self(nums: list[int]) -> list[int]:
answer = [1] * len(nums)
# Pass 1 (left to right): answer[i] = product of everything LEFT of i.
prefix = 1 # nothing to the left of index 0, and the empty product is 1
for i in range(len(nums)):
answer[i] = prefix # use it first...
prefix *= nums[i] # ...then include nums[i] for the next position
# Pass 2 (right to left): multiply in the product of everything RIGHT of i.
suffix = 1 # nothing to the right of the last index
for i in range(len(nums) - 1, -1, -1):
answer[i] *= suffix
suffix *= nums[i]
return answer