Skip to main content
07

Product of Array Except Self

Mediumprefix sum

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Arrays & HashingRead the beginner guide

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, 4 is 2 × 3 × 4 = 24.
  • For every position i, cover up nums[i] with your finger and multiply everything else. That result goes in answer[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

text
Input:  nums = [1, 2, 3, 4]
Output: [24, 12, 8, 6]
iCover upMultiply the restanswer[i]
012 × 3 × 424
121 × 3 × 412
231 × 2 × 48
341 × 2 × 36

Example 2

text
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 except nums[i]. That's n loops of n steps each, O(n²).
    • Divide: multiply everything once (24 for [1, 2, 3, 4]), then answer[i] = 24 / nums[i]. Fast, but the problem forbids division, and it also breaks when the array contains a 0 (you can't divide by zero).

    The key insight

    "Everything except nums[i]" splits into two parts:

    text
    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 i is called a prefix product ("prefix" = the beginning part).
    • The product of everything after i is 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).

    ianswer[i] = prefixthen prefix *= nums[i]
    011 × 1 = 1
    111 × 2 = 2
    222 × 3 = 6
    366 × 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).

    ianswer[i] *= suffixthen suffix *= nums[i]
    36 × 1 = 61 × 4 = 4
    22 × 4 = 84 × 3 = 12
    11 × 12 = 1212 × 2 = 24
    01 × 24 = 2424 × 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: prefix and suffix.

    Common mistakes

    • Multiplying before writing. If you do prefix *= nums[i] before answer[i] = prefix, every answer includes its own number.
    • Starting the running products at 0. Anything times 0 is 0. The "empty product" is 1.
    • Using two extra arrays. Separate prefix[] and suffix[] 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

    js
    /**
     * @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
    }
    ts
    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
    }
    python
    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