Back to Problem
Official 1827 views

Editorial: Product of Array Except Self

by admin ·

3

1 Intuition

answer[i] = (product of everything left of i) × (product of everything right of i).

2 Approach

Fill the output with prefix products in one pass, then multiply in suffix products in a backward pass with a single running variable.

3 Complexity Analysis

Time O(n), Space O(1) extra besides the output.

4 Solution Code

class Solution:
    def productExceptSelf(self, nums: list[int]) -> list[int]:
        n = len(nums)
        out = [1] * n
        for i in range(1, n):
            out[i] = out[i - 1] * nums[i - 1]
        suffix = 1
        for i in range(n - 1, -1, -1):
            out[i] *= suffix
            suffix *= nums[i]
        return out

5 Code Walkthrough

The reference solution below implements the approach step by step.