-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproduct_of_array_except_self.py
More file actions
37 lines (35 loc) · 962 Bytes
/
Copy pathproduct_of_array_except_self.py
File metadata and controls
37 lines (35 loc) · 962 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#solution in n^2
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
output = []
for n in nums:
sumofbefore = 1
sumofafter = 1
index = nums.index(n)
for j in nums[:index]:
sumofbefore *= j
for k in nums[index + 1:]:
sumofafter *= k
output.append(sumofbefore * sumofafter)
return output
# optimal o(n) solution
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = [1] * len(nums)
prefix = 1
for i in range(len(nums)):
res[i] = prefix
prefix *= nums[i]
postfix = 1
for i in range(len(nums) - 1, -1, -1):
res[i] *= postfix
postfix *= nums[i]
return res