Day 14 of 90MediumLeetCode

Product of Array Except Self

For every position, return the product of all the other numbers in the array — without using division.

Pattern
Prefix and suffix products
Time box
25 min
Time
O(n)
Space
O(1) extra

Try it first — give it 25 minutes

0/4 revealed

Stuck? Take one hint at a time. The struggle is where the pattern sticks.

    The problem in plain English

    Return an array answer where answer[i] is the product of every element of nums except nums[i]. You must do it in O(n) time and without the division operator.

    nums = [1, 2, 3, 4] → [24, 12, 8, 6] (for example, answer[1] = 1 × 3 × 4 = 12)

    Start with brute force

    For each i, multiply every other element: O(n²).

    The tempting shortcut is "multiply everything, then divide by nums[i]". It's banned here, and it also breaks on zeros — you can't divide by 0. This is why the problem is interesting.

    Building the intuition

    Draw the array and cover up position i with your finger. What's left is two pieces: the part to the left and the part to the right.

    nums:      1   2   3   4
                    [i=2]
    left of i: 1 × 2 = 2
    right of i:          4
    answer[2] = 2 × 4 = 8

    So answer[i] = prefix[i] × suffix[i], where:

    • prefix[i] = product of nums[0..i−1] (1 when there's nothing to the left)
    • suffix[i] = product of nums[i+1..n−1] (1 when there's nothing to the right)

    Each of those can be built in one pass with a running product. We don't even need two extra arrays: write the prefix products straight into answer, then sweep from the right multiplying in a running suffix.

    The optimal approach

    1. Make answer of length n.
    2. Left pass: running = 1. For i from 0 to n−1: set answer[i] = running, then running *= nums[i].
    3. Right pass: running = 1. For i from n−1 down to 0: answer[i] *= running, then running *= nums[i].
    4. Return answer.

    Notice the order inside each loop: use the running product first, then include nums[i]. That's what keeps nums[i] itself out of its own answer.

    The code

    Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.

    class Solution:
        def productExceptSelf(self, nums: List[int]) -> List[int]:
            n = len(nums)
            answer = [1] * n
    
            # Left pass: answer[i] = product of everything LEFT of i
            running = 1
            for i in range(n):
                answer[i] = running
                running *= nums[i]        # include nums[i] only AFTER using it
    
            # Right pass: multiply in the product of everything RIGHT of i
            running = 1
            for i in range(n - 1, -1, -1):
                answer[i] *= running
                running *= nums[i]
    
            return answer

    Dry run

    nums = [1, 2, 3, 4]

    Left pass (answer[i] = product of everything left of i):

    irunning beforeanswer[i]running after
    0111
    1112
    2226
    36624

    Right pass (multiply in everything right of i):

    irunning beforeanswer[i]running after
    316 × 1 = 64
    242 × 4 = 812
    1121 × 12 = 1224
    0241 × 24 = 2424

    Result: [24, 12, 8, 6].

    Complexity

    • Time: O(n). Two passes.
    • Space: O(1) extra. Only running; the output array doesn't count as extra space by the problem's rules.

    Edge cases and traps

    • One zero. Every answer is 0 except at the zero's position. Prefix/suffix handles it automatically.
    • Two or more zeros. Every answer is 0 — also handled automatically.
    • Negative numbers. Signs just multiply through; nothing special.
    • Wrong loop order. Multiplying running *= nums[i] before writing the answer includes nums[i] in its own product.

    Say it in the interview

    "Division is off the table and breaks on zeros anyway. The product of everything except i is the product of everything to its left times everything to its right. I do a left-to-right pass storing the left product in the answer array, then a right-to-left pass multiplying in a running right product. O(n) time, O(1) extra space."

    Follow-ups interviewers ask

    • "What if division were allowed?" Total product divided by nums[i] — but count zeros: with one zero only that position is non-zero, with two or more everything is zero.
    • "What about overflow?" The problem guarantees products fit in 32 bits; in general you'd use 64-bit integers or work modulo a prime.
    • "Can you explain prefix sums?" Same idea with addition — the next problem, Subarray Sum Equals K, is built on it.

    Practise the same idea

    This is Day 14 of a free 90-day plan 🐸

    90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.

    Get the full roadmap — free