Arrays & Hashing

Prefix and Suffix Products

Product of Array Except Self

1Question

Product of Array Except Self

MediumLeetCode 238 ↗

You are given an array of numbers nums. Return a new array answer where answer[i] is the product of all the numbers in nums except nums[i].

Rules

You must write an algorithm that runs in O(n) time and without using division. Every product fits in a 32-bit integer.

Examples
Example 1
Input: [1,2,3,4]
Output: [24,12,8,6]

For index 0 we multiply the others: 2 × 3 × 4 = 24. For index 3: 1 × 2 × 3 = 6.

Example 2
Input: [-1,1,0,-3,3]
Output: [0,0,9,0,0]

The 0 is in every product except its own. So all other answers are 0, and the answer for the 0 is (−1) × 1 × (−3) × 3 = 9.

Example 3
Input: [2,3]
Output: [3,2]

Each position gets the other number.

Constraints

2 ≤ nums.length ≤ 105

Up to 100,000 numbers. Multiplying all the others for each position is about 10 billion steps. That is too slow, so we need O(n).

−30 ≤ nums[i] ≤ 30

Values are small, and can be negative or zero. A zero changes how the answer looks, so we must handle it.

No division

The easy idea “multiply everything, then divide by nums[i]” is not allowed. It also breaks when a number is 0.

Follow-up

Can you use only O(1) extra space? The output array does not count as extra space. Yes: reuse it.

2Hints

Open one hint at a time. Try to think before you open the next one.

3Pattern

Pattern name

Prefix and Suffix Products

Combine what is on the left with what is on the right, using two running products.

Every answer is made of two parts that never include nums[i]: the product of the left side and the product of the right side. A running product gives us each side in one pass:

answer[i] = (product of nums[0..i-1]) × (product of nums[i+1..n-1])

Pass 1 (left to right) stores the left part. Pass 2 (right to left) multiplies in the right part. Division is never needed.

How to spot this pattern

  • For each position you need “everything except this one”.
  • The operation can be combined step by step (multiply, add, max, min).
  • You are not allowed to “undo” the operation, for example no division.
  • The same left or right work would be repeated for many positions.

4Explanation

The big idea: Make the output array in two passes. We keep one running number each time.

Pass 1: Left to right

Keep prefix, starting at 1. At each i, set answer[i] = prefix, then prefix *= nums[i].

Pass 2: Right to left

Keep suffix, starting at 1. At each i, do answer[i] *= suffix, then suffix *= nums[i].

Why save before multiplying? We want the product of the numbers before position i. If we multiplied nums[i] in first, the position would count itself.

Why does it work? After pass 1, answer[i] holds the left product. In pass 2 we multiply by the right product. Left × right is everything except nums[i].

5Brute Force

For each position, multiply all the other numbers.

Idea

This follows the question word for word. For each position i we:

  • Start with product = 1.
  • Loop over every position j and skip j == i.
  • Multiply the rest, then save the result as answer[i].
Python
def product_except_self_brute(nums):
    n = len(nums)
    answer = []

    for i in range(n):
        product = 1
        for j in range(n):
            if j != i:                # skip the number at position i
                product *= nums[j]
        answer.append(product)

    return answer


print(product_except_self_brute([1, 2, 3, 4]))  # [24, 12, 8, 6]

6Optimal Solution

Two passes: left products first, then right products.

Python
def product_except_self(nums):
    n = len(nums)
    answer = [1] * n

    prefix = 1                        # product of everything to the left
    for i in range(n):
        answer[i] = prefix            # save BEFORE multiplying nums[i]
        prefix *= nums[i]

    suffix = 1                        # product of everything to the right
    for i in range(n - 1, -1, -1):
        answer[i] *= suffix           # combine left and right
        suffix *= nums[i]

    return answer


print(product_except_self([1, 2, 3, 4]))  # [24, 12, 8, 6]

7Time and Space Complexity

Let n be the number of items in the array.

Brute force

Time: O(n²)Space: O(1)

Optimal (prefix and suffix)

Time: O(n)Space: O(1)

How big is the difference?

Approximate number of multiplications:

nBrute force (n²)Two passes (2n)
109020
1,000999,0002,000
100,000about 10 billion200,000

For the biggest input in this problem, the two-pass method does around 50,000 times less work.

8Visualization

Try:Use 1 to 8 whole numbers (from -9 to 9), separated by commas.
Current Element-
Running Product-
Pass-
1
2
3
4

Step Analysis

Click "Next" to begin analysis.
Core Logic:
Pass 1 (left → right): answer[i] = prefix; prefix *= num
Pass 2 (right → left): answer[i] *= suffix; suffix *= num
Result: left product × right product