Advertisement
aero2146

Product of Array Except Self

Dec 29th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.93 KB | None | 0 0
  1. """
  2. Explanation:
  3. This solution works by finding the total multiplication of all the numbers to the left of the current number. Then loop again to find the multiplication of all numbers to the right.
  4.  
  5. If the given array is: [1,2,3,4]
  6. The array would be changed so that every position represents the multiplication of the numbers to the left of it.
  7. [1,2,3,4] --> [1,1,2,6]
  8.  
  9. Now we do the same thing from right to left, thus every position represents the multiplication of the numbers from the right to left.
  10.  
  11. [1,1,2,6] --> [24,12,8,6]
  12. """
  13.  
  14. class Solution:
  15.     def productExceptSelf(self, nums: List[int]) -> List[int]:
  16.         output = [1]*len(nums)
  17.        
  18.         prod = 1
  19.         for i in range(len(nums)):
  20.             output[i] *= prod
  21.             prod *= nums[i]
  22.        
  23.         prod = 1
  24.         for i in range(len(nums)-1, -1, -1):
  25.             output[i] *= prod
  26.             prod *= nums[i]
  27.        
  28.         return output
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement