Product of All Elements Except Self in Python
Given a list of integers, return a list where each element is the product of all other elements except itself, using prefix and suffix products in O(n) time and O(1) extra space.
Python code
20 linesdef product_except_self(nums):
n = len(nums)
result = [1] * n
left_product = 1
for i in range(n):
result[i] = left_product
left_product *= nums[i]
right_product = 1
for i in range(n - 1, -1, -1):
result[i] *= right_product
right_product *= nums[i]
return result
if __name__ == "__main__":
nums = [1, 2, 3, 4]
print(product_except_self(nums))
Output
[24, 12, 8, 6]
How it works
The algorithm uses two passes over the list. First, it computes the product of all elements to the left of each index and stores it in the result list. Then, it traverses from right to left, multiplying each result element by the product of all elements to its right, tracked with a variable. This avoids using division, handling lists with zeros correctly. The time complexity is O(n) with O(1) extra space (excluding the output list).
Common mistakes
- Using division by zero when the list contains zeros
- Forgetting to initialize the right product to 1
- Overwriting result values in the left pass before using them
Variations
- Use multiplication with a nested loop for small lists (O(n^2))
- Use the math.prod function and divide (but fails on zeros)
Real-world use cases
- Computing normalized feature values in machine learning where each feature is scaled by the product of others.
- Generating array-based puzzle outputs in coding assessments.
- Optimizing financial portfolio calculations where each asset's weight depends on the product of others.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.