Skip to content

Commit 8eecf23

Browse files
committed
feat: Add Solution to Product of Array Except Self #239
1 parent ae93e1a commit 8eecf23

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution(object):
2+
def productExceptSelf(self, nums):
3+
"""
4+
TimeComplexity: O(n)
5+
SpaceComplexity: O(n)
6+
"""
7+
n = len(nums)
8+
9+
10+
# prefix product ์ˆ˜ํ–‰
11+
# left๋Š” i๋ฒˆ์งธ ์š”์†Œ ์™ผ์ชฝ์— ์žˆ๋Š” ์š”์†Œ๋“ค์˜ ๊ณฑ
12+
left = [1] * n
13+
for i in range(1, n):
14+
left[i] = left[i - 1] * nums[i - 1]
15+
16+
# suffix product ์ˆ˜ํ–‰
17+
# right๋Š” i๋ฒˆ์งธ ์š”์†Œ ์˜ค๋ฅธ์ชฝ์— ์žˆ๋Š” ์š”์†Œ๋“ค์˜ ๊ณฑ
18+
right = [1] * n
19+
for i in range(n - 2, -1, -1): # ๋ฐฐ์—ด์˜ ๋งˆ์ง€๋ง‰ ์ธ๋ฑ์Šค, [n - 1]์€ ์ด๋ฏธ 1๋กœ ์ดˆ๊ธฐํ™” ๋˜์–ด ์žˆ์œผ๋ฏ€๋กœ
20+
right[i] = right[i + 1] * nums[i + 1]
21+
22+
# ๋‘ ๋ฐฐ์—ด์„ ์ด์šฉํ•˜์—ฌ ์ตœ์ข… ์ถœ๋ ฅ
23+
answer = [1] * n
24+
for i in range(n):
25+
answer[i] = left[i] * right[i]
26+
27+
return answer
28+
29+
30+

0 commit comments

Comments
ย (0)