Skip to content

Commit a1a3394

Browse files
committed
Sync LeetCode submission Runtime - 19 ms (87.52%), Memory - 23.4 MB (50.28%)
1 parent 1283fe7 commit a1a3394

File tree

2 files changed

+20
-18
lines changed

2 files changed

+20
-18
lines changed

0238-product-of-array-except-self/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
<ul>
1919
<li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
2020
<li><code>-30 &lt;= nums[i] &lt;= 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>&nbsp;</p>
Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,24 @@
1+
# Approach 2: Prefix and Suffix Products
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
16
class 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

0 commit comments

Comments
 (0)