LeetCode #238: Product of Array Except Self — a tricky problem that teaches prefix and suffix patterns.
Given an array nums, return an array answer where answer[i] is the product of all elements EXCEPT nums[i]. You cannot use division.
Example:[1, 2, 3, 4] → [24, 12, 8, 6]
answer[0] = 2×3×4 = 24, answer[1] = 1×3×4 = 12, etc.
The Trick — Prefix × Suffix:
For each position, the answer is (product of everything to the LEFT) × (product of everything to the RIGHT).
💭 Time to code! Use the step-by-step approach described above. Don't peek at the solution — try first! 🚀
Complexity: Time O(n), Space O(1) extra (the output array doesn't count)
def productExceptSelf(nums):
n = len(nums)
answer = [1] * n
# Left pass: prefix products
prefix = 1
for i in range(n):
answer[i] = prefix
prefix *= nums[i]
# Right pass: multiply by suffix products
suffix = 1
for i in range(n - 1, -1, -1):
answer[i] *= suffix
suffix *= nums[i]
return answer
productExceptSelf([1, 2, 3, 4])
[24, 12, 8, 6]
productExceptSelf([-1, 1, 0, -3, 3])
[0, 0, 9, 0, 0]