Product of Array Except Self

mediumArrays & Hashing26 stepsJava · Python · C++

For each index, return the product of every other element, without division. The answer at i is (product of everything left of i) × (product of everything right of i): fill left products in one pass, then multiply in right products in a second pass.

▶ Watch the animated trace

Traced input: nums = [1, 2, 3, 4] → [24, 12, 8, 6]. Original problem: neetcode.io/problems/products-of-array-discluding-self

Complexity

BestO(n)
AverageO(n)
WorstO(n)
SpaceO(1)

Two passes. The output array doesn't count as extra space, and the suffix is one variable.

Key idea

Common mistakes

Solution

Java
int[] productExceptSelf(int[] nums) {
    int n = nums.length;
    int[] res = new int[n];
    res[0] = 1;
    for (int i = 1; i < n; i++) {
        res[i] = res[i - 1] * nums[i - 1];
    }
    int suffix = 1;
    for (int i = n - 1; i >= 0; i--) {
        res[i] *= suffix;
        suffix *= nums[i];
    }
    return res;
}
Python
def productExceptSelf(nums: List[int]) -> List[int]:
    n = len(nums)
    res = [1] * n
    for i in range(1, n):
        res[i] = res[i - 1] * nums[i - 1]
    suffix = 1
    for i in range(n - 1, -1, -1):
        res[i] *= suffix
        suffix *= nums[i]
    return res
C++
vector<int> productExceptSelf(vector<int>& nums) {
    int n = nums.size();
    vector<int> res(n, 1);
    for (int i = 1; i < n; i++) {
        res[i] = res[i - 1] * nums[i - 1];
    }
    int suffix = 1;
    for (int i = n - 1; i >= 0; i--) {
        res[i] *= suffix;
        suffix *= nums[i];
    }
    return res;
}

Edge cases

Each one has its own trace in the interactive view.

CaseInputAnswer
One zero
Only the zero's own index gets a non-zero product.
nums = [-1, 1, 0, -3, 3][0, 0, 9, 0, 0]
Two zeros
Every product includes at least one zero.
nums = [0, 0, 2][0, 0, 0]
Two elements
Each answer is simply the other element.
nums = [5, 6][6, 5]
Negatives
Signs multiply normally.
nums = [-1, -2, -3][6, 3, 2]
← Top K Frequent ElementsLongest Consecutive Sequence →