LeetCode 238 Product of Array Except Self - Solution

The core idea

For each position i, the answer is the product of all elements to the left times the product of all elements to the right.

First pass: build prefix products from left to right. prefix[i] holds the product of all elements before index i.

Second pass: traverse from right to left, multiplying each prefix result by the running suffix product.

With nums = [1, 2, 3, 4]:

  • Prefix products: [1, 1, 2, 6] (product of elements to the left)
  • Suffix products: [24, 12, 4, 1] (product of elements to the right)
  • Answer: [1×24, 1×12, 2×4, 6×1] = [24, 12, 8, 6]