Skip to content

Commit 0470660

Browse files
committed
Add solution for Product of Array Except Self
1 parent dd58e5e commit 0470660

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""
2+
# Approach
3+
λͺ¨λ“  μ›μ†ŒλΌλ¦¬ κ³±ν•œ λ‹€μŒμ— nums 배열을 μˆœνšŒν•˜λ©° κ·Έ 값을 ν•΄λ‹Ή μ›μ†Œλ‘œ λ‚˜λˆˆλ‹€.
4+
μ΄λ•Œ 0의 κ°œμˆ˜μ™€ 0을 μ œμ™Έν•œ 곱의 값도 같이 κ΅¬ν•œλ‹€.
5+
0이 2개 이상이면 정닡은 λͺ¨λ‘ 0이며,
6+
0이 1개면 0을 μ œμ™Έν•œ 곱의 값을 μ‚¬μš©ν•œλ‹€.
7+
8+
# Complexity
9+
- Time complexity: O(n)
10+
11+
- Space complexity: O(n)
12+
"""
13+
14+
15+
# Code
16+
class Solution:
17+
def productExceptSelf(self, nums: List[int]) -> List[int]:
18+
product = 1
19+
non_zero_product = 1
20+
zero_count = 0
21+
for num in nums: # O(n) Time complexity
22+
if num == 0:
23+
zero_count += 1
24+
non_zero_product *= 1
25+
else:
26+
non_zero_product *= num
27+
product *= num
28+
29+
if zero_count > 1:
30+
return [0] * len(nums) # O(n) space complexity
31+
32+
answer = [] # O(n) space complexity
33+
for i in range(len(nums)): # O(n) Time complexity
34+
if nums[i] == 0:
35+
answer.append(non_zero_product)
36+
else:
37+
answer.append(int(product / nums[i]))
38+
return answer

0 commit comments

Comments
Β (0)