Product of Array Except Self
The problem
Section titled “The problem”You get an integer array. Return a new array where entry i is the product of all
elements except nums[i]. Do it in O(n) time and without division.
nums = [1, 2, 3, 4] -> [24, 12, 8, 6] (24 = 2 * 3 * 4, 12 = 1 * 3 * 4, ...)Key insight
Section titled “Key insight”Brute force multiplies everything else for each index: O(n²). Dividing the total
product by nums[i] is banned, and it also breaks on zeros.
Look at what “everything except i” really is: the product of everything to the
left of i times the product of everything to the right. Both are running
products. First pass, left to right: store the running left product in the output
array. Second pass, right to left: multiply each slot by a running right product. The
output array doubles as the prefix storage, so no extra array is needed.
Show solutionHide solution
def product_except_self(nums: list[int]) -> list[int]: n = len(nums) result = [1] * n
prefix = 1 # product of everything left of i for i in range(n): result[i] = prefix prefix *= nums[i]
suffix = 1 # product of everything right of i for i in range(n - 1, -1, -1): result[i] *= suffix suffix *= nums[i] return resultexport function productExceptSelf(nums: number[]): number[] { const n = nums.length; const result: number[] = new Array(n).fill(1);
let prefix = 1; // product of everything left of i for (let i = 0; i < n; i++) { result[i] = prefix; prefix *= nums[i]; }
let suffix = 1; // product of everything right of i for (let i = n - 1; i >= 0; i--) { result[i] *= suffix; suffix *= nums[i]; } return result;}class Solution { public int[] productExceptSelf(int[] nums) { int n = nums.length; int[] result = new int[n];
int prefix = 1; // product of everything left of i for (int i = 0; i < n; i++) { result[i] = prefix; prefix *= nums[i]; }
int suffix = 1; // product of everything right of i for (int i = n - 1; i >= 0; i--) { result[i] *= suffix; suffix *= nums[i]; } return result; }}Complexity
Section titled “Complexity”- Time: O(n) — two linear passes.
- Space: O(1) extra — only two scalar variables. The output array is not counted, as the problem allows.
Watch out for
Section titled “Watch out for”- Start both running products at 1, not 0. The first element has nothing to its left, so its left product is the empty product, 1. The same goes for the last element’s right side.
- Update the answer before the running product. Write
result[i] = prefixfirst, thenprefix *= nums[i]. Reversing them includesnums[i]in its own answer. - Zeros need no special case with this method. The division approach does: one zero makes every other slot 0, two zeros make everything 0.
Variations
Section titled “Variations”Maximum Product Subarray (LeetCode 152)
Section titled “Maximum Product Subarray (LeetCode 152)”Find the contiguous subarray with the largest product. The trick: track both the max and min product ending at each position. A negative number can flip the smallest product into the largest.
Find Pivot Index (LeetCode 724)
Section titled “Find Pivot Index (LeetCode 724)”Find the index where the sum on the left equals the sum on the right. The trick:
the same prefix and suffix idea with sums. Keep the total, and the left sum as you go;
the right sum is total - left - nums[i].
Range Sum Query - Immutable (LeetCode 303)
Section titled “Range Sum Query - Immutable (LeetCode 303)”Answer many “sum from i to j” queries fast. The trick: build a prefix-sum array
once, then each query is prefix[j + 1] - prefix[i] in O(1).