ToolMight Logo
MediumArrays & HashingPrefix and Suffix ProductsSpace Optimization

Product of Array Except Self

Compute the array of products excluding each element without division. Progress from separate left/right product arrays to O(1) auxiliary space.

Optimal Time
O(n)
Optimal Space
O(1)
Primary Pattern
Prefix and Suffix Products
Visualizer
Open Interactive View →

Problem Statement

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

Examples & Constraints

Example 1
Input: nums = [1, 2, 3, 4]
Output: [24, 12, 8, 6]
Explanation: answer[0] = 2*3*4 = 24, answer[1] = 1*3*4 = 12, answer[2] = 1*2*4 = 8, answer[3] = 1*2*3 = 6.
Example 2
Input: nums = [-1, 1, 0, -3, 3]
Output: [0, 0, 9, 0, 0]
Explanation: Only index 2 omits the zero, leaving (-1)*1*(-3)*3 = 9.
Constraints
  • 2 <= nums.length <= 10^5
  • -30 <= nums[i] <= 30
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

Pattern Recognition & Core Invariant

How to Spot This Pattern

Whenever every index needs a combination of all elements before it and after it without inverse operations (like division when zeros can appear), split into a prefix pass and a suffix pass.

Core Invariant

answer[i] equals (product of nums[0..i-1]) multiplied by (product of nums[i+1..n-1]); storing prefixes in the output buffer lets a scalar suffix variable finish the calculation in-place.

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. Explicit Left & Right Product Arrays
O(n)O(n)Build separate leftProducts and rightProducts arrays, then multiply leftProducts[i] * rightProducts[i] for every index.
2. Prefix & Suffix Running Products (O(1) Extra Space)Optimal
O(n)O(1)First pass: store the running product of all elements to the left of i. Second pass: traverse from right to left while multiplying by the running suffix product in O(1) auxiliary space.

1. Explicit Left & Right Product Arrays

TimeO(n)
SpaceO(n)

Build separate leftProducts and rightProducts arrays, then multiply leftProducts[i] * rightProducts[i] for every index.

Time ComplexityO(n)

Three linear loops over n elements.

Space ComplexityO(n)

Allocates two auxiliary arrays of size n alongside the output array.

How It Works

Splitting Left and Right Dependencies

Rather than mutating the result array twice, store both sides explicitly:

  1. left[i] = product of all elements strictly before i (left[0] = 1).
  2. right[i] = product of all elements strictly after i (right[n - 1] = 1).
  3. answer[i] = left[i] * right[i].

This uses O(n) extra space, making the invariants easy to inspect before optimizing space to O(1).

Step-by-Step Dry Run

Execution Trace·Step 1 of 3
1Build left Array ([1, 2, 3, 4])

left[0] = 1, left[1] = 1, left[2] = 2, left[3] = 6.

State:left = [1, 1, 2, 6]
Strengths
  • +Zero in-place mutation confusion
  • +Crystal-clear prefix and suffix separation
Trade-offs
  • -Allocates 2 extra O(n) arrays instead of reusing the return buffer

Reference Implementation

Complete implementation for Explicit Left & Right Product Arrays in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def product_except_self_arrays(nums: list[int]) -> list[int]:
n = len(nums)
left = [1] * n
right = [1] * n
for i in range(1, n):
left[i] = left[i - 1] * nums[i - 1]
for i in range(n - 2, -1, -1):
right[i] = right[i + 1] * nums[i + 1]
return [left[i] * right[i] for i in range(n)]

2. Prefix & Suffix Running Products (O(1) Extra Space)

Optimal
TimeO(n)
SpaceO(1)

First pass: store the running product of all elements to the left of i. Second pass: traverse from right to left while multiplying by the running suffix product in O(1) auxiliary space.

Time ComplexityO(n)

We perform one forward pass of length N and one backward pass of length N. Total operations are 2N = O(n).

Space ComplexityO(1)

The output array does not count toward auxiliary space complexity. Only a single scalar suffix variable is used.

How It Works

Why Division Is Forbidden

If division were allowed, you could calculate the total product of all elements P and set ans[i] = P / nums[i].
However:

  1. If the array contains a zero 0, division by zero crashes or produces an undefined result.
  2. If there are multiple zeros, every element is zero.
  3. The problem explicitly tests your ability to decompose array dependencies into prefix and suffix relationships.

The Decomposition Mental Model: Left * Right

Notice that for any index i:
product_except_i = (product of all elements left of i) * (product of all elements right of i)

We can compute this in two linear sweeps using the output array itself:

  1. Prefix Sweep (Left to Right):
  • Initialize answer[0] = 1 (no elements exist to the left of index 0).
  • For i from 1 to n - 1: answer[i] = answer[i - 1] * nums[i - 1]
  • Now, answer[i] holds the product of all elements to the left of i.
  1. Suffix Sweep (Right to Left):
  • Maintain a running scalar variable suffix = 1.
  • For i from n - 1 down to 0:
  • Multiply answer[i] *= suffix.
  • Update suffix *= nums[i] for the next element to the left.
  1. Return answer.

Step-by-Step Dry Run

Execution Trace·Step 1 of 4
1nums = [1, 2, 3, 4]

Initialize answer array. Prefix pass sets answer[0] = 1.

State:answer = [1, ?, ?, ?]
Strengths
  • +Optimal O(n) runtime with zero division operations
  • +O(1) auxiliary memory using the output array for prefix products
Trade-offs
  • -Requires two full sequential passes over the array

Reference Implementation

Complete implementation for Prefix & Suffix Running Products (O(1) Extra Space) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def product_except_self(nums: list[int]) -> list[int]:
n = len(nums)
res = [1] * n
# Step 1: Prefix products
for i in range(1, n):
res[i] = res[i - 1] * nums[i - 1]
# Step 2: Suffix products
suffix = 1
for i in range(n - 1, -1, -1):
res[i] *= suffix
suffix *= nums[i]
return res
if __name__ == "__main__":
test1 = [1, 2, 3, 4]
test2 = [-1, 1, 0, -3, 3]
print("test1:", product_except_self(test1))
print("test2:", product_except_self(test2))
Interactive Visualizer

Trace Array & Matrix mechanics in memory

Step through custom inputs in the Array & Matrix visualizer to inspect pointer updates, array shifts, and call-stack state alongside Product of Array Except Self.

Open Array & Matrix visualizer

Frequently Asked Questions

Why can't we just divide the total product by each element?

Any zero entry inside nums would cause division by zero (and force special counting for 1 zero vs 2+ zeros). Prefix-suffix decomposition avoids division completely and handles zero counts naturally.

Does the output array count toward the space complexity?

In interview complexity analysis, the required output array (res / answer) is excluded from auxiliary space. With only a scalar suffix integer extra, auxiliary space is O(1).

Can both prefix and suffix be multiplied in a single loop?

Yes, by advancing two indices i from 0 and n - 1 - i from the end simultaneously while updating running prefix and suffix scalars, though two separate directional loops are cleaner and faster for CPU cache prefetching.

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • Single zero ([-1, 1, 0, -3, 3]) produces 0 everywhere except at the zero's own index (9).
  • Two or more zeros ([0, 4, 0, 2]) yield an all-zero array because every index excludes at most one zero.
  • Two-element array ([a, b]) returns [b, a].
  • Odd number of negative elements flips signs cleanly without overflow (values bounded so prefix/suffix fit 32-bit int).

Common Bugs to Avoid

  • Computing totalProduct / nums[i] which crashes on zero entries or misses multiple-zero cases.
  • Overwriting res[i] while multiplying suffix without maintaining a separate running suffix accumulator.
  • Starting the backward pass at n - 2 instead of n - 1 and missing the suffix multiplier update for nums[n - 1].

Interview Follow-Up Variations

  • How would you handle the same requirement if prefix/suffix products could overflow 32-bit integers? Use 64-bit integers (`long long` / `long`) or big integers.
  • Constructing Left & Right Minimum/Maximum arrays (e.g., Trapping Rain Water, Candy distribution) follows this exact two-pass decomposition.

Related Problems

All problems
EasyArrays & Hashing

Two Sum

Find indices of two array elements summing to target. Compare O(n²) brute-force scanning against O(n) one-pass complement lookup with a Hash Map.

Pattern: Hash Map
O(n) · O(n)
Solve
EasyArrays & Hashing

Contains Duplicate

Check whether any integer repeats inside an array. Compare early-exit O(n) Hash Set membership testing against O(1)-space in-place sorting.

Pattern: Hash Set
O(n) · O(n)
Solve
EasyArrays & Hashing

Valid Anagram

Check whether string t is an anagram of string s. Compare O(n log n) canonical sorting against an O(n) fixed 26-letter frequency bucket balance.

Pattern: Frequency Counting
O(n) · O(1)
Solve