smj007

Untitled

Apr 6th, 2025
516
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.55 KB | None | 0 0
  1. TC - O(n)
  2. SC - O(1)
  3.  
  4. class Solution:
  5.     def productExceptSelf(self, nums: List[int]) -> List[int]:
  6.        
  7.         product = [1]*len(nums)
  8.  
  9.         # do a forward pass and accumulate the answers
  10.         for i in range(1, len(nums)):
  11.             product[i] = product[i-1]*nums[i-1]
  12.  
  13.         reverse_cum_product = 1
  14.         # do a backward pass and accumulate the answers again
  15.         for i in range(len(nums)-1, -1, -1):
  16.             product[i] = product[i]*reverse_cum_product
  17.             reverse_cum_product *= nums[i]
  18.  
  19.         return product
Advertisement
Add Comment
Please, Sign In to add comment