Skip to content
Problem 238 · LeetCode 238(opens in a new tab)

Product of Array Except Self

MediumArrays

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.

Try it on LeetCode(opens in a new tab)
  1. Brute forceO(n²)
  2. Left and right product arraysO(n)
  3. Two running productsO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 numbersVerdict
Brute forceO(n²)
Mention it, then move on
Left and right product arraysO(n)
Passes; uses two extra arrays
Two running productsO(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

  1. 1Clarify. Can there be zeros or negatives? Is division really off the table? Does the output array count as extra space?
  2. 2Give the brute force. Multiply all the others for each slot; say it is O(n²).
  3. 3Split the product. Everything except i is everything before i times everything after i.
  4. 4Code two passes. Write the left products into the answer, then sweep back with one running number.
  5. 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?