File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments