smj007

Untitled

Jul 30th, 2023
1,072
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.66 KB | None | 0 0
  1. # Approach: maintain a product prefix. However you do not do the same for product suffix, for that what you got to do is
  2. # start calcualting answer backwards and as you go from end to start calculate product suffix.
  3.  
  4. class Solution:
  5.     def productExceptSelf(self, nums: List[int]) -> List[int]:
  6.        
  7.         product = 1
  8.         prefix = [1 for i in range(len(nums))]
  9.  
  10.         for i in range(1, len(nums)):
  11.             prefix[i] = prefix[i-1]*nums[i-1]
  12.  
  13.         suffix = 1
  14.         ans = [1 for i in range(len(nums))]
  15.  
  16.         for i in range(len(nums)-1, -1, -1):
  17.             ans[i] = prefix[i]*suffix
  18.             suffix = suffix*nums[i]
  19.  
  20.         return ans
Advertisement
Add Comment
Please, Sign In to add comment