You are given an array of integers, nums. Build a new array of the same length where position i holds the product of every number in nums other than nums[i].
Two rules make it interesting: your solution has to run in O(n) time, and you are not allowed to divide. The inputs are chosen so that every product you might need fits in a 32-bit signed integer.
Example 1
Input: nums = [2, 3, 1, 4] Output: [12, 8, 24, 6] Why: slot 0 is 3 × 1 × 4 = 12, slot 1 is 2 × 1 × 4 = 8, and so on
2 more examples and the constraints
Example 2
Input: nums = [3, 0, -2, 5] Output: [0, -30, 0, 0] Why: only the slot of the 0 avoids multiplying by 0
Example 3
Input: nums = [-1, -1] Output: [-1, -1] Why: each slot is just the other number
Constraints
- 2 ≤ length of nums ≤ 100,000
- −30 ≤ nums[i] ≤ 30
- Any product of a prefix or a suffix of nums fits in a 32-bit integer
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Brute forceO(n²)
- Left and right product arraysO(n)
- Two running productsO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 numbers | Verdict |
|---|---|---|---|
| Brute force | O(n²) | Mention it, then move on | |
| Left and right product arrays | O(n) | Passes; uses two extra arrays | |
| Two running products | O(n) | Best; O(1) extra space |
n = how many numbers are in nums. The output array is not counted as extra space.
Edge cases to test
- One zero. [3, 0, -2, 5]: every slot is 0 except the slot of the 0 itself.
- Two or more zeros. [0, 4, 0]: every slot is 0, including both zeros.
- Only two numbers. [5, 7] swaps them: [7, 5].
- Negative numbers. Signs multiply like any other value; [-2, -3, -4] gives [12, 8, 6].
Common mistakes
- Multiplying everything and dividing by nums[i], which fails on zeros and breaks the rules.
- Updating the running product before writing it into answer[i], so each slot includes its own number.
- Starting the right pass at 0 instead of 1, which wipes out every slot.
How to talk through it
- 1Clarify. Can there be zeros or negatives? Is division really off the table? Does the output array count as extra space?
- 2Give the brute force. Multiply all the others for each slot; say it is O(n²).
- 3Split the product. Everything except i is everything before i times everything after i.
- 4Code two passes. Write the left products into the answer, then sweep back with one running number.
- 5Test out loud. Run the one-zero and two-zero cases before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?