Given an integer array nums, return an array output where output[i] is the product of all the elements of nums except nums[i].
Each product is guaranteed to fit in a 32-bit integer.
Follow-up: Could you solve it in O ( n ) O(n) time without using the division operation?
Example 1:
Input: nums = [1,2,4,6]
Output: [48,24,12,8] Example 2:
Input: nums = [-1,0,1,2,3]
Output: [0,-6,0,0,0]
In [7]:
def productExceptSelf(nums):
left_prod=1
res = [1]*len(nums)
for i in range(len(nums)):
res[i]=left_prod
left_prod *= nums[i]
right_prod=1
for i in range(len(nums)-1,-1,-1):
res[i]*=right_prod
right_prod*=nums[i]
return res
In [8]:
productExceptSelf([1,2,4,6])
Out[8]:
[48, 24, 12, 8]
In [9]:
[1]*5
Out[9]:
[1, 1, 1, 1, 1]