Skip to content

Commit d436185

Browse files
committed
Solve product-of-array-except-self with python
1 parent 9024ec5 commit d436185

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
class Solution:
2+
# Space complexity: O(n)
3+
# Time complexity: O(n)
4+
def _v1(self, nums: list[int]) -> list[int]:
5+
prefix = [1]
6+
for num in nums[:-1]:
7+
prefix.append(prefix[-1] * num)
8+
9+
reverse_nums = nums[::-1]
10+
postfix = [1]
11+
for num in reverse_nums[:-1]:
12+
postfix.append(postfix[-1] * num)
13+
postfix = postfix[::-1]
14+
15+
return [prefix[i] * postfix[i] for i in range(len(nums))]
16+
17+
# Space complexity: O(1)
18+
# Time complexity: O(n)
19+
def _v2(self, nums: list[int]) -> list[int]:
20+
n = len(nums)
21+
answer = [1] * n
22+
23+
# 1. save prefix product to temp
24+
temp = 1
25+
for i in range(1, n):
26+
temp *= nums[i - 1]
27+
answer[i] *= temp
28+
29+
# 2. save postfix product to temp
30+
temp = 1
31+
for i in range(n - 2, -1, -1):
32+
temp *= nums[i + 1]
33+
answer[i] *= temp
34+
35+
return answer
36+
37+
38+
def productExceptSelf(self, nums: List[int]) -> List[int]:
39+
# index -> product
40+
# 0 -> - [1, 2, 3]
41+
# 1 -> [0] - [2, 3]
42+
# 2 -> [0, 1] - [3]
43+
# 3 -> [0, 1, 2] -
44+
return self._v2(nums)
45+
46+

0 commit comments

Comments
 (0)