Read-only web browser

Solutions

Browse the interview solutions folder with syntax highlighting.

product-of-array-except-self.py

array-hashing/product-of-array-except-self.py · Python · 746 B · 2025-09-21 16:00

Back to folder
# Accumulate the product of elements by traversing the array from left to right, and then from right to left
# arrays
# Optimized, O(n) time, O(1) space
def product_except_self(nums: list[int]) -> list[int]:
    n = len(nums)
    ans = [1] * n
    acc = 1
    for i in range(1, len(nums)):
        acc *= nums[i - 1]
        ans[i] = acc

    acc = 1
    for i in range(len(nums) - 2, -1, -1):
        acc *= nums[i + 1]
        ans[i] *= acc
    return ans

# Brute force, O(n^2) time, O(1) space
def product_except_self(nums: list[int]) -> list[int]:
    n = len(nums)
    ans = []
    for i in range(n):
        prod = 1
        for j in range(n):
            if i != j:
                prod *= nums[j]
        ans.append(prod)
    return ans