Skip to content

Commit 78d9149

Browse files
committed
add solution: product-of-array-except-self
1 parent 1580f71 commit 78d9149

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
'''
2+
# 238. Product of Array Except Self
3+
4+
use prefix and suffix to calculate the product of the array, except self.
5+
6+
## Time and Space Complexity
7+
8+
```
9+
TC: O(n)
10+
SC: O(n)
11+
```
12+
13+
### TC is O(n):
14+
- iterating through the list twice, to calculate both prefix and suffix products. = O(n)
15+
16+
### SC is O(n):
17+
- storing the prefix and suffix in the answer list. = O(n)
18+
'''
19+
class Solution:
20+
def productExceptSelf(self, nums: List[int]) -> List[int]:
21+
n = len(nums)
22+
answer = [1] * n
23+
24+
# prefix
25+
for i in range(1, n):
26+
answer[i] *= nums[i - 1] * answer[i - 1]
27+
28+
# suffix
29+
suffix_product = 1
30+
for i in range(n - 1, -1, -1):
31+
answer[i] *= suffix_product
32+
suffix_product *= nums[i]
33+
34+
return answer

0 commit comments

Comments
 (0)