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.

Medium Python 3.9+ Aug 9, 2026 Algorithms & data structures 14 views 0 copies

Python code

20 lines
Python 3.9+
def 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

stdout
[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

  1. Use multiplication with a nested loop for small lists (O(n^2))
  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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.