Product of Array Except Self (LeetCode 238): Solution and Explanation
Given an integer array, build an output array where each position holds the product of every other element in the input. You must do it in linear time without using division.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force computes each answer from scratch: for position i, multiply every element except nums[i]. That is O(n²). The tempting shortcut is to multiply everything once and divide by nums[i], but the problem forbids division, and division breaks anyway when the array contains a zero.
Look at what the answer for index i actually is. It is the product of everything to the left of i times the product of everything to the right of i. Both of those are running products that can be built incrementally. The product of everything left of i + 1 is just the product left of i multiplied by nums[i], and the same holds from the other side. So two linear sweeps, one from the left and one from the right, give every answer.
The natural way to code that is two helper arrays, prefix and suffix, followed by one multiplication per index. The reference solution goes one step further and saves the extra memory. It writes the prefix products straight into the result array on the forward pass, using a single running variable. On the backward pass it keeps another running variable for the suffix product and multiplies it into each slot. The output array is required anyway, so the only additional storage is two integers.
Approach: Prefix and suffix products in the output array
- Create
resof length n filled with 1. - Set
prefix = 1. Loopifrom 0 to n - 1: storeres[i] = prefix, then updateprefix *= nums[i]. Nowres[i]holds the product of all elements to the left ofi. - Set
postfix = 1. Loopifrom n - 1 down to 0: multiplyres[i] *= postfix, then updatepostfix *= nums[i]. - After the backward pass, each
res[i]equals the left product times the right product. - Return
res.
Step-by-step example
nums = [1, 2, 3, 4]
- Forward pass: i = 0 stores 1 (prefix becomes 1), i = 1 stores 1 (prefix 2), i = 2 stores 2 (prefix 6), i = 3 stores 6 (prefix 24). res = [1, 1, 2, 6].
- Backward pass, i = 3: res[3] = 6 × 1 = 6, postfix becomes 4.
- i = 2: res[2] = 2 × 4 = 8, postfix becomes 12.
- i = 1: res[1] = 1 × 12 = 12, postfix becomes 24.
- i = 0: res[0] = 1 × 24 = 24. Return [24, 12, 8, 6].
Code: Python, Java, C++
1class Solution:
2 def productExceptSelf(self, nums: List[int]) -> List[int]:
3 res = [1] * (len(nums))
4 prefix = 1
5 for i in range(len(nums)):
6 res[i] = prefix
7 prefix *= nums[i]
8 postfix = 1
9 for i in range(len(nums) - 1, -1, -1):
10 res[i] *= postfix
11 postfix *= nums[i]
12 return res1class Solution {
2 public int[] productExceptSelf(int[] nums) {
3 int[] res = new int[nums.length];
4 int prefix = 1;
5 for (int i = 0; i < nums.length; i++) {
6 res[i] = prefix;
7 prefix *= nums[i];
8 }
9 int postfix = 1;
10 for (int i = nums.length - 1; i >= 0; i--) {
11 res[i] *= postfix;
12 postfix *= nums[i];
13 }
14 return res;
15 }
16}1class Solution {
2public:
3 vector<int> productExceptSelf(vector<int>& nums) {
4 vector<int> res(nums.size(), 1);
5 int prefix = 1;
6 for (int i = 0; i < nums.size(); i++) {
7 res[i] = prefix;
8 prefix *= nums[i];
9 }
10 int postfix = 1;
11 for (int i = nums.size() - 1; i >= 0; i--) {
12 res[i] *= postfix;
13 postfix *= nums[i];
14 }
15 return res;
16 }
17};Time and space complexity
O(n)
There are exactly two passes over the array, each doing constant work per element.
O(1) extra
Aside from the output array, which the problem requires and does not count, only the two running variables prefix and postfix are used.
Other approaches
Separate prefix and suffix arrays (time O(n), space O(n))
Build left[i] and right[i] in two arrays, then set res[i] = left[i] * right[i]. It is easier to reason about when learning the idea, but it uses two extra arrays.
Total product with zero handling (time O(n), space O(1) extra)
Multiply all non-zero elements and count zeros, then divide or return zeros as appropriate. It is O(n) but uses division, which the problem disallows, and the zero cases are easy to get wrong.
Common mistakes
- Updating
prefixbefore writing it intores[i]. That includesnums[i]in its own product, which is exactly what must be excluded. - Initializing
reswith zeros instead of ones. The backward pass multiplies into the existing values, so a zero start wipes everything out. - Reaching for division and then special-casing zeros. One zero makes every other answer zero, and two zeros make all answers zero, so the division path has several branches to get right and is forbidden anyway.
- Worrying about overflow in Java or C++ without reading the constraints. The problem guarantees every prefix and suffix product fits in a 32-bit integer.
Frequently asked questions
How do you solve Product of Array Except Self without division?
Compute, for each index, the product of everything to its left and everything to its right, using one forward pass and one backward pass. Multiplying those two products gives the answer for that index.
How is the space O(1) if we return an array?
By convention the output array does not count as extra space. The algorithm stores the prefix products in that output array and only adds two scalar variables.
What happens when the array contains zeros?
Nothing special is needed. A zero simply makes the running prefix or suffix zero from that point on, which produces the correct zeros in the answer.
Why not just divide the total product by each element?
The problem forbids it, and it fails when an element is zero because you cannot divide by zero. The prefix and suffix method avoids both issues.