product-of-array-except-self

This commit is contained in:
2022-04-21 17:06:14 +05:30
parent d86e3334b1
commit 80245886a1
3 changed files with 58 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
from functools import reduce
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
# We can divide this problem by finding the prefix and
# postfix products of a given element and then multiplying
# them together
result = [0] * len(nums)
# Find prefix products, i.e, for ith element, store
# product of 0 to a[i - 1]
prefix = 1
for i, num in enumerate(nums):
result[i] = prefix
prefix *= num
# Find suffix products by iterating from the last, and
# combine them with prefix in the same step to reduce cost
suffix = 1
for i in range(len(nums) - 1, -1, -1):
result[i] *= suffix
suffix *= nums[i]
return result