Return an array where each element is the product of all other elements.
This problem follows the Prefix/Suffix Product pattern, commonly found in the Arrays & Hashing category. Recognizing this pattern is key to solving it efficiently in an interview setting.
Two passes: build prefix products left-to-right, then suffix products right-to-left.
Two passes replace division — the prefix pass captures everything to the left, the suffix pass captures everything to the right.
result = [1] * len(nums)
prefix = 1
for i in range(len(nums)):
result[i] = prefix
prefix *= nums[i]
suffix = 1
for i in range(len(nums) - 1, -1, -1):
result[i] *= suffix
suffix *= nums[i]
return resultPractice Product of Array Except Self and similar Arrays & Hashing problems with flashcards. Build pattern recognition through active recall.
Practice this problem