Skip to content

Commit 2f629c2

Browse files
committed
Add detailed comments to Product of Array Except Self solution
1 parent e65b197 commit 2f629c2

File tree

1 file changed

+22
-14
lines changed

1 file changed

+22
-14
lines changed
Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,32 @@
11
"""
22
Constraints:
3-
1. 2 <= nums.length <= 10^5
4-
2. -30 <= nums[i] <= 30
5-
3. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer
3+
- ๋‚˜๋ˆ—์…ˆ ์—ฐ์‚ฐ ์‚ฌ์šฉ ๋ถˆ๊ฐ€๋Šฅ
4+
- O(n) ์‹œ๊ฐ„ ๋ณต์žก๋„๋กœ ๊ตฌํ˜„ํ•ด์•ผ ํ•จ
5+
- ๋ชจ๋“  prefix/suffix ๊ณฑ์€ 32๋น„ํŠธ ์ •์ˆ˜ ๋ฒ”์œ„ ๋‚ด์— ์žˆ์Œ
66
77
Time Complexity: O(n)
8-
- ๋ฐฐ์—ด์„ ๋‘ ๋ฒˆ ์ˆœํšŒํ•˜๋ฏ€๋กœ O(n)
8+
- ๋ฐฐ์—ด์„ ๋‘ ๋ฒˆ๋งŒ ์ˆœํšŒ
99
1010
Space Complexity: O(1)
11-
- ์ถœ๋ ฅ ๋ฐฐ์—ด(answer)์„ ์ œ์™ธํ•˜๋ฉด ์ถ”๊ฐ€ ๊ณต๊ฐ„์ด ์ƒ์ˆ˜๋งŒํผ๋งŒ ํ•„์š”(left, right ๋ณ€์ˆ˜)
11+
- ์ถœ๋ ฅ ๋ฐฐ์—ด ์™ธ ์ถ”๊ฐ€ ๊ณต๊ฐ„์€ ์ƒ์ˆ˜๋งŒ ์‚ฌ์šฉ (left, right ๋ณ€์ˆ˜)
1212
1313
ํ’€์ด ๋ฐฉ๋ฒ•:
14-
1. answer ๋ฐฐ์—ด์„ 1๋กœ ์ดˆ๊ธฐํ™” (๊ณฑ์…ˆ์—์„œ๋Š” 1์ด ์˜ํ–ฅ์„ ์ฃผ์ง€ ์•Š์Œ)
15-
2. ์™ผ์ชฝ์—์„œ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์ˆœํšŒ:
16-
- answer[i]์— ํ˜„์žฌ๊นŒ์ง€์˜ left ๋ˆ„์ ๊ฐ’์„ ๊ณฑํ•จ
17-
- left *= nums[i]๋กœ ๋‹ค์Œ์„ ์œ„ํ•ด left ๊ฐ’์„ ์—…๋ฐ์ดํŠธ
18-
3. ์˜ค๋ฅธ์ชฝ์—์„œ ์™ผ์ชฝ์œผ๋กœ ์ˆœํšŒ (range(n-1, -1, -1) ์‚ฌ์šฉ):
19-
- answer[i]์— ํ˜„์žฌ๊นŒ์ง€์˜ right ๋ˆ„์ ๊ฐ’์„ ๊ณฑํ•จ
20-
- right *= nums[i]๋กœ ๋‹ค์Œ์„ ์œ„ํ•ด right ๊ฐ’์„ ์—…๋ฐ์ดํŠธ
14+
- ๊ฐ ์œ„์น˜์˜ ๊ฒฐ๊ณผ๋Š” (์™ผ์ชฝ ๋ชจ๋“  ์š”์†Œ์˜ ๊ณฑ) * (์˜ค๋ฅธ์ชฝ ๋ชจ๋“  ์š”์†Œ์˜ ๊ณฑ)
15+
- ๋‘ ๋ฒˆ์˜ ์ˆœํšŒ๋กœ ์ด๋ฅผ ๊ณ„์‚ฐ:
16+
1. ์™ผ์ชฝ -> ์˜ค๋ฅธ์ชฝ: ๊ฐ ์œ„์น˜์— ์™ผ์ชฝ ๋ชจ๋“  ์š”์†Œ์˜ ๋ˆ„์  ๊ณฑ ์ €์žฅ
17+
2. ์˜ค๋ฅธ์ชฝ -> ์™ผ์ชฝ: ๊ฐ ์œ„์น˜์— ์˜ค๋ฅธ์ชฝ ๋ชจ๋“  ์š”์†Œ์˜ ๋ˆ„์  ๊ณฑ์„ ๊ณฑํ•จ
18+
19+
์˜ˆ์‹œ: nums = [1, 2, 3, 4]
20+
1๋‹จ๊ณ„ ํ›„: answer = [1, 1, 2, 6]
21+
2๋‹จ๊ณ„ ํ›„: answer = [24, 12, 8, 6]
2122
"""
2223

24+
# Final result = (product of all elements on the left side) * (product of all elements on the right side)
25+
26+
# Step 1: Initialize result array with 1s
27+
# Step 2: Traverse from left to right, storing cumulative product of left side
28+
# Step 3: Traverse from right to left, multiplying with cumulative product of right side
29+
# nums = [1,2,3,4]
2330
class Solution:
2431
def productExceptSelf(self, nums: List[int]) -> List[int]:
2532
n = len(nums)
@@ -29,10 +36,11 @@ def productExceptSelf(self, nums: List[int]) -> List[int]:
2936
for i in range(n):
3037
answer[i] *= left
3138
left *= nums[i]
32-
39+
# answer = [1, 1, 2, 6] at this point
3340
right = 1
3441
for i in range(n-1, -1, -1):
3542
answer[i] *= right
3643
right *= nums[i]
37-
44+
3845
return answer
46+
# answer = [24,12,8,6]

0 commit comments

Comments
ย (0)