nathanwailes

LeetCode 238 - Product of Array Except Self - 2022.12.31 solution

Dec 31st, 2022
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. class Solution:
  2.     def productExceptSelf(self, nums: List[int]) -> List[int]:
  3.         """ How to solve it: The normal way to do this would be to multiply all the numbers in the input into
  4.        a single product, then go through the input again and divide by each number to get the product for that
  5.        index.  Since we can't use the division operation, we need to figure out how to only use the multiplication
  6.        operator.  So we need two additional arrays, one for the product to the left of the given index, the
  7.        other for the product to the right of the given index.
  8.        To do it in O(1) extra space complexity, we can use the result list to store the left-products and then
  9.        iterate from the right again with a single variable to store the right product.
  10.        """
  11.         res = []
  12.  
  13.         # Fill out the left-products
  14.         for i in range(len(nums)):
  15.             if not res:
  16.                 res.append(1)
  17.             else:
  18.                 res.append(nums[i-1] * res[i-1])
  19.        
  20.         right_product = 1
  21.         for i in range(len(nums)-1, -1, -1):
  22.             if i == len(nums) - 1:
  23.                 continue
  24.             else:
  25.                 right_product *= nums[i+1]
  26.                 res[i] = res[i] * right_product
  27.         return res
Advertisement
Add Comment
Please, Sign In to add comment