File tree Expand file tree Collapse file tree 2 files changed +20
-18
lines changed
0238-product-of-array-except-self Expand file tree Collapse file tree 2 files changed +20
-18
lines changed Original file line number Diff line number Diff line change 1818<ul >
1919 <li><code>2 <= nums.length <= 10<sup>5</sup></code></li>
2020 <li><code>-30 <= nums[i] <= 30</code></li>
21- <li>The product of any prefix or suffix of <code>nums </code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li>
21+ <li>The input is generated such that <code>answer[i] </code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li>
2222</ul >
2323
2424<p >  ; </p >
Original file line number Diff line number Diff line change 1+ # Approach 2: Prefix and Suffix Products
2+
3+ # Time: O(n)
4+ # Space: O(1)
5+
16class Solution :
27 def productExceptSelf (self , nums : List [int ]) -> List [int ]:
38 n = len (nums )
4-
5- answer = [0 ] * n
6-
7- answer [0 ] = 1
8- for i in range (1 , n ):
9- answer [i ] = answer [i - 1 ] * nums [i - 1 ]
10-
11- right = 1
12- for i in range (n - 1 , - 1 , - 1 ):
13- answer [i ] = answer [i ] * right
14- right *= nums [i ]
9+ ans = [1 ] * n
10+
11+ # Calculate prefix products
12+ prefix = 1
13+ for i in range (n ):
14+ ans [i ] = prefix
15+ prefix *= nums [i ]
16+
17+ # Calculate suffix products and combine with prefix products
18+ suffix = 1
19+ for i in range (n - 1 , - 1 , - 1 ):
20+ ans [i ] *= suffix
21+ suffix *= nums [i ]
1522
16- return answer
17-
18- # Time: O(n) - traversing the elements two times independently
19- # Space: O(1) - one additional variable - right
20-
21-
23+ return ans
2224
You can’t perform that action at this time.
0 commit comments