We can solve this by calculating the prefix products and the suffix products. For any element at index i, its result is (product of all elements to its left) * (product of all elements to its right).
- Initialize an
answerarray of the same length asnums, filled with 1s. - Initialize
prefix = 1. Iterate from left to right:answer[i] = prefixprefix *= nums[i]
- Now
answer[i]contains the product of all elements to the left ofi. - Initialize
suffix = 1. Iterate from right to left:answer[i] *= suffixsuffix *= nums[i]
- Now
answer[i]contains the product of all elements exceptnums[i].
- Time Complexity: O(N), two passes over the array.
- Space Complexity: O(1) if we don't count the output array, otherwise O(N).
def product_except_self(nums):
n = len(nums)
answer = [1] * n
# Prefix product
prefix = 1
for i in range(n):
answer[i] = prefix
prefix *= nums[i]
# Suffix product combined with the result
suffix = 1
for i in range(n - 1, -1, -1):
answer[i] *= suffix
suffix *= nums[i]
return answer