Product of Array Except Self
Return an array where output[i] is the product of all elements in nums except nums[i], without using the division operation in O(n) time.
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
- 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.
Prefix & Suffix Running Products (O(1) Extra Space)
Optimal ApproachFirst 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.
We perform one forward pass of length N and one backward pass of length N. Total operations are 2N = O(n).
The output array does not count toward auxiliary space complexity. Only a single scalar suffix variable is used.
Underlying algorithmic logic
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:
- If the array contains a zero
0, division by zero crashes or produces an undefined result. - If there are multiple zeros, every element is zero.
- 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:
- Prefix Sweep (Left to Right):
- Initialize
answer[0] = 1(no elements exist to the left of index 0). - For
ifrom1ton - 1:answer[i] = answer[i - 1] * nums[i - 1] - Now,
answer[i]holds the product of all elements to the left ofi.
- Suffix Sweep (Right to Left):
- Maintain a running scalar variable
suffix = 1. - For
ifromn - 1down to0: - Multiply
answer[i] *= suffix. - Update
suffix *= nums[i]for the next element to the left.
- Return
answer.
Step-by-step execution walkthrough
Initialize answer array. Prefix pass sets answer[0] = 1.
answer[1] = 1*1 = 1. answer[2] = 1*2 = 2. answer[3] = 2*3 = 6.
suffix = 1. i = 3: answer[3] = 6*1 = 6; suffix = 1*4 = 4. i = 2: answer[2] = 2*4 = 8; suffix = 4*3 = 12.
i = 1: answer[1] = 1*12 = 12; suffix = 12*2 = 24. i = 0: answer[0] = 1*24 = 24.
- •Optimal O(n) runtime with zero division operations
- •O(1) auxiliary memory using the output array for prefix products
- •Requires two full sequential passes over the array
Code Implementations
Ready-to-useCopy & paste production-ready solutions for Prefix & Suffix Running Products (O(1) Extra Space) in your language of choice
def product_except_self(nums: list[int]) -> list[int]:n = len(nums)res = [1] * n# Step 1: Prefix productsfor i in range(1, n):res[i] = res[i - 1] * nums[i - 1]# Step 2: Suffix productssuffix = 1for i in range(n - 1, -1, -1):res[i] *= suffixsuffix *= nums[i]return resif __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))
Understand Array & Matrix Visually
Explore sequential element access, subsegment manipulations, insertion, deletion, and 2D grid matrix walks. Test live edge cases and watch memory state transitions step-by-step.
Frequently Asked Questions
Related Logic & Algorithm Problems
Two Sum
Find the two numbers in an array that sum up to a target value. The quintessential problem for learning how to trade memory for speed using a Hash Map.
Contains Duplicate
Determine if any value appears at least twice in an integer array. A foundational problem for mastering constant-time hash lookups vs sorting trade-offs.
Valid Anagram
Determine whether two strings have the exact same character frequencies. A core problem demonstrating the power of fixed-size frequency buckets over O(n log n) sorting.