class Solution:
# @param {integer[]} nums
# @return {integer[]}
def productExceptSelf(self, nums):
p = 1
n = len(nums)
output = []
for i in range(0,n):
output.append(p)
p = p * nums[i]
p = 1
for i in range(n1,1,1):
output[i] = output[i] * p
p = p * nums[i]
return output
Python solution (Accepted), O(n) time, O(1) space

another approach if no overflow concerns.
def productExceptSelf(self, nums): cntZero = nums.count(0) if not cntZero: prod = reduce(operator.mul,nums) return [prod/x for x in nums] res = [0]*len(nums) if cntZero == 1: res[nums.index(0)] = reduce(operator.mul,(x for x in nums if x)) return res



@qeatzy replace
reduce(operator.mul,(x for x in nums if x))
toreduce(lambda x, y: x*y if y else x, nums)
can be much faster.


@hqpdash is this solution O(n) space instead of O(1) since we are using another output array to store numbers



In the case someone might be interested. This is the same approach but combining two pointers in one for loop.
class Solution(object): def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ if not nums: return False arr = [1] * len(nums) pi = pj = 1 for i in range(len(nums)): j = 1i arr[i]*=pi; arr[j]*=pj pi *= nums[i]; pj *= nums[j] return arr

@qeatzy in interviews, this question tends to have an additional constraint that you can't use division in your solution.