238. Product of Array Except Self
Given an integer array
nums, return an arrayanswersuch thatanswer[i]is equal to the product of all the elements ofnumsexceptnums[i].The product of any prefix or suffix of
numsis guaranteed to fit in a 32-bit integer.You must write an algorithm that runs in
O(n)time and without using the division operation.Example 1:
Input: nums = [1,2,3,4]
Output: [24,12,8,6]Example 2:
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)
prefix_products = [1] * n
suffix_products = [1] * n
result = [1] * n
# Calculate prefix products
for i in range(1, n):
prefix_products[i] = prefix_products[i - 1] * nums[i - 1]
# Calculate suffix products
for i in range(n - 2, -1, -1):
suffix_products[i] = suffix_products[i + 1] * nums[i + 1]
# Calculate result by multiplying prefix and suffix products
for i in range(n):
result[i] = prefix_products[i] * suffix_products[i]
return result