Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Method : 1
- class Solution:
- def productExceptSelf(self, nums: List[int]) -> List[int]:
- zero_count=0
- total=1
- for i in nums:
- if i==0:
- zero_count+=1
- else:
- total*=i
- ans=[]
- for i in range(len(nums)):
- if zero_count==0:
- ans.append(total//nums[i])
- elif zero_count==1:
- if nums[i]==0:
- ans.append(total)
- else:
- ans.append(0)
- else:
- ans.append(0)
- return ans
- #Method 2:Sometimes division is not allowed in the interviews, Most optimised solution
- class Solution:
- def productExceptSelf(self, nums: List[int]) -> List[int]:
- n = len(nums)
- ans = [1] * n
- prefix = 1
- for i in range(n):
- ans[i] = prefix
- prefix *= nums[i]
- suffix = 1
- for i in range(n - 1, -1, -1):
- ans[i] *= suffix
- suffix *= nums[i]
- return ans
Advertisement
Add Comment
Please, Sign In to add comment