roadmap/arrays-hashing/Product of Array Except Self

Product of Array Except Self

MediumAmazonGoogleMetaMicrosoft
Solve on LeetCode ↗

Given an array nums, return an array output where output[i] is the product of all elements except nums[i]. Must run in O(n) without division.

For each index i: answer = (product of all elements left of i) × (product of all elements right of i). Compute prefix products left-to-right, then multiply by suffix products right-to-left in a second pass.

Prefix × suffix pass

Pass 1: result[i] = product of nums[0..i-1]. Pass 2: running suffix product from right, multiply into result[i].

Time
O(n)
Space
O(1) extra

Two passes, output array doesn't count as extra space.

Python
def productExceptSelf(self, nums: List[int]) -> List[int]:
    n = len(nums)
    result = [1] * n
    
    # Left pass: result[i] = product of nums[0..i-1]
    prefix = 1
    for i in range(n):
        result[i] = prefix
        prefix *= nums[i]
    
    # Right pass: multiply by product of nums[i+1..n-1]
    suffix = 1
    for i in range(n-1, -1, -1):
        result[i] *= suffix
        suffix *= nums[i]
    
    return result
Array with zeros: prefix/suffix naturally handle zeros
Single element: output is [1]

What pattern do you think this problem uses?

Progress is saved on this device