Product of Array Except Self

Free with account Updated Nov 19, 2026 · 5 min read
On this page

    Problem statement

    Given an integer array nums, return an array out where out[i] is the product of every element except nums[i]. Do it in O(n) time without using division. Follow-up: use O(1) extra space, not counting the output array. You may assume every such product fits in a 32-bit integer.

    A short array problem that teaches prefix and suffix accumulation, the same idea behind prefix sums, but with multiplication. The "no division" rule exists because division fails as soon as the array contains a zero. Original problem: LeetCode 238.

    Example

    Each output is the product of the other three numbers: out[1] = 2 · 4 · 5 = 40.
    Each output is the product of the other three numbers: out[1] = 2 · 4 · 5 = 40.
    Input:  [2, 3, 4, 5]
    Output: [60, 40, 30, 24]
    Input:  [3, 0, 2, 4]
    Output: [0, 24, 0, 0]       # only out[1] skips the zero

    Constraints (assumed)

    • 2 ≤ n ≤ 10⁵; −30 ≤ nums[i] ≤ 30.
    • Every product of all-but-one element fits in 32 bits.

    What this question tests

    • Splitting "everything except i" into everything left of i times everything right of i.
    • Two passes, and reusing the output array as working space to reach O(1) extra memory.
    • Handling zeros and negatives without special cases.

    Questions to ask first

    1. Is division allowed? (Here: no. Even if it were, zeros need careful handling.)
    2. Can there be zeros or negative numbers? (Here: yes, both.)
    3. Does the output array count as extra space? (Here: no.)
    4. Can the products overflow? (Here: assume they fit; otherwise use 64-bit or big integers.)