238. Product of Array Except Self
Given an integer array nums
, return an array answer
such that answer[i]
is equal to the product of all the elements of nums
except nums[i]
.
The product of any prefix or suffix of nums
is 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.
Note: Notice how the left and right are computed after
updating the current ans[i] element, so that ans[i]
is not contributing to the products.
Also note, how left and right needs to start at 1
def productExceptSelf(nums: List[int]):
ans = []
left = 1
for n in nums:
ans.append(left)
left *= n
L = len(nums)
right = 1
for i in reversed(range(L)):
ans[i] *= right
right *= nums[i]
return ans
Comments
Post a Comment