Product of Array Except Self
LeetCode 238 · Medium · solution, intuition & step-by-step walkthrough
answer[i] = prefix_product[i] × suffix_product[i].
This is how I solved Product of Array Except Self (LeetCode 238), a medium problem from the Prefix Sum pattern. Below: the intuition, the approach step by step, my accepted Python code and the 2 versions I wrote on the way, animated test cases and a line-by-line debugger.
Intuition
The answer at i is (product of everything left of i) × (product of everything right of i). Build the left products in one pass and the right products in a second pass — no division needed, so zeros are handled naturally.
Approach
- 1
First pass left→right: arr[i] = product of nums[0..i-1].
- 2
Second pass right→left with a running product of nums[i+1..].
- 3
Multiply the running right product into arr[i].
- 4
The final version reuses the output array, so extra space is O(1).
How I solved it · from first idea to final
Two helper arrays, multiplied at the end.
Fold the suffix product into the output.
Prefix and suffix arraysPythonO(n) time · O(n) space
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
"""
prefix arr - 1,1,2,6
suffix arr - 24,12,4,1
"""
n = len(nums)
prefix_arr = [1]*n
suffix_arr = [1]*n
left = 1
for i in range(1,n):
left = left*nums[i-1]
prefix_arr[i]=left
right = 1
for i in range(n-2,-1,-1):
right = right*nums[i+1]
suffix_arr[i]=right
for i in range(n):
prefix_arr[i]=prefix_arr[i]*suffix_arr[i]
return prefix_arrIn-place suffix passPythonO(n) time · O(1) extra
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
"""
prefix arr - 1,1,2,6
suffix arr - 24,12,4,1
"""
n = len(nums)
arr = [1]*n
left = 1
for i in range(1,n):
left = left*nums[i-1]
arr[i]=left
right = 1
for i in range(n-2,-1,-1):
right = right*nums[i+1]
arr[i]=arr[i]*right
return arrProduct of Array Except Self — FAQ
What is the intuition behind Product of Array Except Self?
The answer at i is (product of everything left of i) × (product of everything right of i). Build the left products in one pass and the right products in a second pass — no division needed, so zeros are handled naturally.
How do you solve Product of Array Except Self (LeetCode 238)?
1. First pass left→right: arr[i] = product of nums[0..i-1]. 2. Second pass right→left with a running product of nums[i+1..]. 3. Multiply the running right product into arr[i]. 4. The final version reuses the output array, so extra space is O(1).
What is the time and space complexity of Product of Array Except Self?
Time: O(n). Space: O(1) extra (output excluded). (Accepted approach: In-place suffix pass.)
What are common mistakes in Product of Array Except Self?
Dividing the total product breaks on zeros.
Is there more than one way to solve Product of Array Except Self?
Prefix and suffix arrays (O(n) time · O(n) space): Two helper arrays, multiplied at the end. In-place suffix pass (O(n) time · O(1) extra): Fold the suffix product into the output.