#238
Medium
Prefix Sum

Product of Array Except Self

Return an array where each value is the product of all other elements.

ArrayPrefix Sum

Pattern fit

This is not sum but the same prefix-suffix decomposition idea: each answer is left product times right product.

Key observation

You never need division if you build left products and then sweep from the right.

Target complexity

O(n) / O(1) extra

How to break down the solution cleanly

1

This is not sum but the same prefix-suffix decomposition idea: each answer is left product times right product.

2

You never need division if you build left products and then sweep from the right.

3

Define what the cumulative state means.

4

Build the prefix in one forward pass.

Reference implementation

Python
# Generic pattern template
prefix = [0] * (len(nums) + 1)
for i, value in enumerate(nums):
    prefix[i + 1] = prefix[i] + value

range_sum = prefix[r + 1] - prefix[l]

Common pitfalls

warning

Reaching for division and breaking on zeros.

warning

Allocating separate full left and right arrays unnecessarily.

Common follow-ups

How does the right-to-left sweep remove one array?

What changes if there are many zeros?

Continue with related problems

Build repeatable depth inside the Prefix Sum cluster before moving on.

view_weekBack to the pattern page
LeetCode 238. Product of Array Except Self Guide | Interview AiBox