nathanwailes

LeetCode 238 - Product of Array Except Self - 2023.10.06 solution

Oct 5th, 2023
919
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.77 KB | None | 0 0
  1. class Solution:
  2.     def productExceptSelf(self, nums: List[int]) -> List[int]:
  3.         """ Solution: Have one list of the products going from R->L.
  4.        Then work through the list, just keeping a variable for
  5.        the L->R product.
  6.        Then, for each index, multiply the value at i in the R->L list
  7.        with the variable storing the L->R product.
  8.        """
  9.  
  10.         r_to_l = [None for n in nums]
  11.         for i in range(len(nums)-1, -1, -1):
  12.             if i == len(nums)-1:
  13.                 r_to_l[i] = 1
  14.             else:
  15.                 r_to_l[i] = r_to_l[i+1] * nums[i+1]
  16.         l_to_r = 1
  17.  
  18.         products = []
  19.         for i in range(len(nums)):
  20.             products.append(l_to_r * r_to_l[i])
  21.             l_to_r *= nums[i]
  22.         return products
Advertisement
Add Comment
Please, Sign In to add comment