imashutosh51

Product of Array Except self

Oct 16th, 2022 (edited)
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.08 KB | None | 0 0
  1. #Method : 1
  2. class Solution:
  3.     def productExceptSelf(self, nums: List[int]) -> List[int]:
  4.         zero_count=0
  5.         total=1
  6.         for i in nums:
  7.             if i==0:
  8.                 zero_count+=1
  9.             else:
  10.                 total*=i
  11.         ans=[]
  12.  
  13.         for i in range(len(nums)):
  14.             if zero_count==0:
  15.                 ans.append(total//nums[i])
  16.             elif zero_count==1:
  17.                 if nums[i]==0:
  18.                     ans.append(total)
  19.                 else:
  20.                     ans.append(0)
  21.             else:
  22.                 ans.append(0)
  23.         return ans
  24.        
  25.  
  26.  
  27. #Method 2:Sometimes division is not allowed in the interviews, Most optimised solution
  28. class Solution:
  29.     def productExceptSelf(self, nums: List[int]) -> List[int]:
  30.         n = len(nums)
  31.         ans = [1] * n
  32.  
  33.         prefix = 1
  34.         for i in range(n):
  35.             ans[i] = prefix
  36.             prefix *= nums[i]
  37.  
  38.         suffix = 1
  39.         for i in range(n - 1, -1, -1):
  40.             ans[i] *= suffix
  41.             suffix *= nums[i]
  42.  
  43.         return ans
  44.  
  45.  
Advertisement
Add Comment
Please, Sign In to add comment