Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def productExceptSelf(self, nums: List[int]) -> List[int]:
- """ How to solve it: The normal way to do this would be to multiply all the numbers in the input into
- a single product, then go through the input again and divide by each number to get the product for that
- index. Since we can't use the division operation, we need to figure out how to only use the multiplication
- operator. So we need two additional arrays, one for the product to the left of the given index, the
- other for the product to the right of the given index.
- To do it in O(1) extra space complexity, we can use the result list to store the left-products and then
- iterate from the right again with a single variable to store the right product.
- """
- res = []
- # Fill out the left-products
- for i in range(len(nums)):
- if not res:
- res.append(1)
- else:
- res.append(nums[i-1] * res[i-1])
- right_product = 1
- for i in range(len(nums)-1, -1, -1):
- if i == len(nums) - 1:
- continue
- else:
- right_product *= nums[i+1]
- res[i] = res[i] * right_product
- return res
Advertisement
Add Comment
Please, Sign In to add comment