Skip to content

Commit 2063129

Browse files
authored
Merge pull request #1768 from hi-rachel/main
[hi-rachel] WEEK 02 solutions
2 parents b8c099d + 8e8234a commit 2063129

File tree

5 files changed

+267
-1
lines changed

5 files changed

+267
-1
lines changed

β€Ž3sum/hi-rachel.py

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,64 @@
1-
# O(n^2) time, O(n) space
1+
"""
2+
https://leetcode.com/problems/3sum/
3+
4+
문제 μ„€λͺ…:
5+
μ •λ ¬λ˜μ§€ μ•Šμ€ μ •μˆ˜ λ°°μ—΄ numsκ°€ μ£Όμ–΄μ§ˆ λ•Œ,
6+
μ„Έ 수의 합이 0이 λ˜λŠ” λͺ¨λ“  μœ λ‹ˆν¬ν•œ triplet을 μ°ΎλŠ” 문제.
7+
8+
쑰건:
9+
- 쀑볡 쑰합은 ν—ˆμš©λ˜μ§€ μ•ŠμŒ.
10+
- 예: [-1, 0, 1]κ³Ό [0, -1, 1]은 같은 μ‘°ν•©μ΄λ―€λ‘œ ν•˜λ‚˜λ§Œ 포함.
11+
12+
풀이 μ „λž΅:
13+
1. 배열을 μ •λ ¬ν•œλ‹€.
14+
2. 첫 번째 수λ₯Ό κ³ μ •ν•œ λ’€, λ‚˜λ¨Έμ§€ 두 수λ₯Ό νˆ¬ν¬μΈν„°λ‘œ νƒμƒ‰ν•œλ‹€.
15+
- 합이 0보닀 μž‘μœΌλ©΄ leftλ₯Ό 증가
16+
- 합이 0보닀 크면 rightλ₯Ό κ°μ†Œ
17+
- 합이 0이면 정닡에 μΆ”κ°€, 쀑볡 λ°©μ§€ μ²˜λ¦¬λ„ ν•¨κ»˜ μˆ˜ν–‰
18+
19+
TC: O(n^2), μ •λ ¬ O(n log n) + νˆ¬ν¬μΈν„° O(n^2)
20+
SC: O(1), 좜λ ₯ 곡간 result μ œμ™Έ
21+
"""
22+
23+
from typing import List
24+
25+
26+
class Solution:
27+
def threeSum(self, nums: List[int]) -> List[List[int]]:
28+
nums.sort()
29+
result = []
30+
31+
for i in range(len(nums) - 2):
32+
if i > 0 and nums[i] == nums[i - 1]:
33+
continue # 쀑볡 제거
34+
35+
left, right = i + 1, len(nums) - 1
36+
37+
while left < right:
38+
total = nums[i] + nums[left] + nums[right]
39+
# 쑰건 λ§Œμ‘±μ‹œ 정닡에 μΆ”κ°€
40+
if total == 0:
41+
result.append([nums[i], nums[left], nums[right]])
42+
# 같은 값을 κ°€μ§„ leftκ°€ μ—¬λŸ¬ 개 μžˆλ‹€λ©΄, 쀑볡 κ±΄λ„ˆλœ€
43+
while left < right and nums[left] == nums[left + 1]:
44+
left += 1
45+
# 같은 값을 κ°€μ§„ rightκ°€ μ—¬λŸ¬ 개 μžˆλ‹€λ©΄, 쀑볡 κ±΄λ„ˆλœ€
46+
while left < right and nums[right] == nums[right - 1]:
47+
right -= 1
48+
left += 1
49+
right -= 1
50+
# 총합이 0보닀 μž‘μœΌλ©΄, 더 큰 μˆ˜κ°€ ν•„μš”ν•˜λ‹ˆκΉŒ leftλ₯Ό 였λ₯Έμͺ½μœΌλ‘œ 이동
51+
elif total < 0:
52+
left += 1
53+
# 총합이 0보닀 크면, 더 μž‘μ€ μˆ˜κ°€ ν•„μš”ν•˜λ‹ˆκΉŒ rightλ₯Ό μ™Όμͺ½μœΌλ‘œ 이동
54+
else:
55+
right -= 1
256

57+
return result
58+
59+
60+
61+
# O(n^2) time, O(n) space
362
class Solution:
463
def threeSum(self, nums: List[int]) -> List[List[int]]:
564
triplets = set()

β€Žclimbing-stairs/hi-rachel.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""
2+
https://leetcode.com/problems/climbing-stairs/description/
3+
4+
ν•œ λ²ˆμ— 1계단 ν˜Ήμ€ 2계단 였λ₯Ό 수 있음
5+
1: 1
6+
2: 2
7+
3: 1 + 1 + 1, 1 + 2, 2 + 1 => 3
8+
4: 1 + 1 + 1 + 1, 1 + 1 + 2, 2 + 1 + 1, 1 + 2 + 1, 2 + 2 => 5
9+
5: 1 + 1 + 1 + 1 + 1,
10+
1 + 1 + 1 + 2,
11+
1 + 1 + 2 + 1 + 1,
12+
1 + 2 + 1 + 1,
13+
2 + 1 + 1 + 1,
14+
2 + 2 + 1,
15+
2 + 1 + 2,
16+
1 + 2 + 2,
17+
=> 8
18+
19+
steps[n] = steps[n - 1] + steps[n - 2]
20+
21+
TC: O(n)
22+
SC: O(n)
23+
"""
24+
25+
class Solution:
26+
def climbStairs(self, n: int) -> int:
27+
if n == 1:
28+
return 1
29+
elif n == 2:
30+
return 2
31+
steps = [0] * n
32+
steps[0] = 1
33+
steps[1] = 2
34+
for i in range(2, n):
35+
steps[i] = steps[i - 2] + steps[i - 1]
36+
return steps[n - 1]
37+
38+
"""
39+
λ³€μˆ˜ 2개둜 μ΅œμ ν™”
40+
곡간 λ³΅μž‘λ„ O(1) κ°œμ„  풀이
41+
"""
42+
class Solution:
43+
def climbStairs(self, n: int) -> int:
44+
if n == 1:
45+
return 1
46+
elif n == 2:
47+
return 2
48+
49+
prev1 = 1
50+
prev2 = 2
51+
52+
for i in range(2, n):
53+
prev1, prev2 = prev2, prev1 + prev2
54+
return prev2
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
https://leetcode.com/problems/product-of-array-except-self/description/
3+
4+
문제: μ •μˆ˜ λ°°μ—΄ numsκ°€ μ£Όμ–΄μ‘Œμ„ λ•Œ, 각 μ›μ†Œλ₯Ό μ œμ™Έν•œ λ‚˜λ¨Έμ§€ μ›μ†Œλ“€μ˜ 곱을 λ°˜ν™˜ν•˜μ„Έμš”.
5+
단, λ‚˜λˆ„κΈ° 연산을 μ‚¬μš©ν•˜μ§€ 말고 O(n) μ‹œκ°„ λ³΅μž‘λ„λ‘œ ν•΄κ²°ν•˜μ„Έμš”.
6+
7+
핡심 아이디어:
8+
각 μ›μ†Œλ₯Ό κΈ°μ€€μœΌλ‘œ:
9+
- μ™Όμͺ½μ— μžˆλŠ” μ›μ†Œλ“€μ˜ κ³±
10+
- 였λ₯Έμͺ½μ— μžˆλŠ” μ›μ†Œλ“€μ˜ κ³±
11+
을 각각 κ³±ν•΄μ£Όλ©΄, 자기 μžμ‹ μ„ μ œμ™Έν•œ 전체 곱이 λœλ‹€.
12+
13+
μ˜ˆμ‹œ: [1, 2, 3, 4]
14+
- 인덱슀 0: μ™Όμͺ½(μ—†μŒ) Γ— 였λ₯Έμͺ½(2Γ—3Γ—4) = 24
15+
- 인덱슀 1: μ™Όμͺ½(1) Γ— 였λ₯Έμͺ½(3Γ—4) = 12
16+
- 인덱슀 2: μ™Όμͺ½(1Γ—2) Γ— 였λ₯Έμͺ½(4) = 8
17+
- 인덱슀 3: μ™Όμͺ½(1Γ—2Γ—3) Γ— 였λ₯Έμͺ½(μ—†μŒ) = 6
18+
19+
TC: O(n) - 배열을 두 번 순회
20+
SC: O(1) - κ²°κ³Ό 배열을 μ œμ™Έν•œ μΆ”κ°€ 곡간 μ‚¬μš©ν•˜μ§€ μ•ŠμŒ
21+
"""
22+
23+
from typing import List
24+
25+
class Solution:
26+
def productExceptSelf(self, nums: List[int]) -> List[int]:
27+
n = len(nums)
28+
result = [1] * n # κ²°κ³Ό λ°°μ—΄ μ΄ˆκΈ°ν™”
29+
30+
# 1단계: μ™Όμͺ½μ—μ„œ 였λ₯Έμͺ½μœΌλ‘œ μˆœνšŒν•˜λ©° μ™Όμͺ½ μ›μ†Œλ“€μ˜ κ³± 계산
31+
left_product = 1
32+
for i in range(n):
33+
result[i] = left_product # ν˜„μž¬ μœ„μΉ˜μ— μ™Όμͺ½ κ³± μ €μž₯
34+
left_product *= nums[i] # λ‹€μŒμ„ μœ„ν•΄ ν˜„μž¬ μ›μ†Œ κ³±ν•˜κΈ°
35+
36+
# 2단계: 였λ₯Έμͺ½μ—μ„œ μ™Όμͺ½μœΌλ‘œ μˆœνšŒν•˜λ©° 였λ₯Έμͺ½ μ›μ†Œλ“€μ˜ κ³± 계산
37+
right_product = 1
38+
for i in range(n - 1, -1, -1):
39+
result[i] *= right_product # κΈ°μ‘΄ μ™Όμͺ½ 곱에 였λ₯Έμͺ½ κ³± κ³±ν•˜κΈ°
40+
right_product *= nums[i] # λ‹€μŒμ„ μœ„ν•΄ ν˜„μž¬ μ›μ†Œ κ³±ν•˜κΈ°
41+
42+
return result

β€Žvalid-anagram/hi-rachel.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""
2+
https://leetcode.com/problems/valid-anagram/description/
3+
두 λ¬Έμžμ—΄μ΄ μ• λ„ˆκ·Έλž¨μΈμ§€ ν™•μΈν•˜λŠ” ν•¨μˆ˜λ₯Ό μž‘μ„±ν•˜μ„Έμš”.
4+
μ• λ„ˆκ·Έλž¨μ΄λž€ 두 λ¬Έμžμ—΄μ΄ μ€‘λ³΅λœ μ•ŒνŒŒλ²³μ„ 같은 개수만큼 ν¬ν•¨ν•˜κ³  μžˆλŠ” 것을 μ˜λ―Έν•©λ‹ˆλ‹€.
5+
6+
TC: O(n)
7+
SC: O(k), k = μ•ŒνŒŒλ²³ 개수
8+
"""
9+
10+
from collections import defaultdict
11+
12+
class Solution:
13+
def isAnagram(self, s: str, t: str) -> bool:
14+
def makeMap(s: str):
15+
str_map = defaultdict(int)
16+
for char in s:
17+
str_map[char] += 1
18+
return str_map
19+
20+
return makeMap(s) == makeMap(t)
21+
22+
23+
"""
24+
μ •λ ¬ 풀이
25+
26+
TC: O(nlogn)
27+
SC: O(1)
28+
"""
29+
def isAnagram(s: str, t: str) -> bool:
30+
return sorted(s) == sorted(t)
31+
32+
"""
33+
Counter μ‚¬μš© 풀이
34+
35+
TC: O(n)
36+
SC: O(k)
37+
"""
38+
from collections import Counter
39+
40+
def isAnagram(s: str, t: str) -> bool:
41+
return Counter(s) == Counter(t)

β€Žvalidate-binary-search-tree/hi-rachel.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,73 @@
1+
"""
2+
λͺ¨λ“  μ™Όμͺ½ μ„œλΈŒνŠΈλ¦¬λŠ” ν˜„μž¬ λ…Έλ“œλ³΄λ‹€ μž‘μ•„μ•Ό ν•˜κ³ ,
3+
λͺ¨λ“  였λ₯Έμͺ½ μ„œλΈŒνŠΈλ¦¬λŠ” ν˜„μž¬ λ…Έλ“œλ³΄λ‹€ 컀야 ν•œλ‹€.
4+
5+
이걸 μœ„ν•΄μ„œ λ²”μœ„(min/max)λ₯Ό μž¬κ·€λ‘œ 내렀보내야 ν•œλ‹€.
6+
7+
TC: O(n), λͺ¨λ“  λ…Έλ“œ 1λ²ˆμ”© 탐색
8+
SC: O(h), μž¬κ·€ 호좜 μŠ€νƒ, hλŠ” 트리 높이
9+
"""
10+
11+
from typing import Optional
12+
# Definition for a binary tree node.
13+
class TreeNode:
14+
def __init__(self, val=0, left=None, right=None):
15+
self.val = val
16+
self.left = left
17+
self.right = right
18+
19+
class Solution:
20+
def isValidBST(self, root: Optional[TreeNode]) -> bool:
21+
def validate(node, low, high):
22+
if not node:
23+
return True # λΉ„μ–΄μžˆλŠ” λ…Έλ“œλŠ” BST
24+
# ν˜„μž¬ λ…Έλ“œκ°€ λ²”μœ„ 밖이면 BST 쑰건 μœ„λ°°
25+
if not (low < node.val < high):
26+
return False
27+
# μ™Όμͺ½μ€ μ΅œλŒ€κ°’μ„ ν˜„μž¬ λ…Έλ“œλ³΄λ‹€ μž‘κ²Œ μ œν•œ
28+
# 였λ₯Έμͺ½μ€ μ΅œμ†Œκ°’μ„ ν˜„μž¬ λ…Έλ“œλ³΄λ‹€ 크게 μ œν•œ
29+
return (validate(node.left, low, node.val) and
30+
validate(node.right, node.val, high))
31+
32+
return validate(root, float('-inf'), float('inf'))
33+
34+
35+
"""
36+
μŠ€νƒ 풀이
37+
38+
- BSTμ—μ„œ μ€‘μœ„ μˆœνšŒν•˜λ©΄ 항상 μ˜€λ¦„μ°¨μˆœμ΄μ–΄μ•Ό ν•œλ‹€λŠ” μ„±μ§ˆμ„ μ΄μš©ν•œ 방법
39+
- μ€‘μœ„ 순회: μ™Όμͺ½ β†’ ν˜„μž¬ λ…Έλ“œ β†’ 였λ₯Έμͺ½
40+
- BSTλŠ” μ€‘μœ„ 순회 μ‹œ 값이 항상 증가해야 ν•˜λ―€λ‘œ, (μ˜€λ¦„μ°¨μˆœ)
41+
이전 λ…Έλ“œ(prev)보닀 ν˜„μž¬ λ…Έλ“œ 값이 μž‘κ±°λ‚˜ κ°™μœΌλ©΄ 잘λͺ»λœ BST
42+
43+
TC: O(n), λͺ¨λ“  λ…Έλ“œ 1λ²ˆμ”© 탐색
44+
SC: O(h), μ΅œλŒ€ μŠ€νƒ 깊이 = 트리 높이
45+
"""
46+
47+
class Solution:
48+
def isValidBST(self, root: Optional[TreeNode]) -> bool:
49+
stack = []
50+
prev = None # 이전 μ€‘μœ„ 순회 κ°’
51+
52+
while stack or root:
53+
# μ™Όμͺ½ λκΉŒμ§€ 탐색
54+
while root:
55+
stack.append(root)
56+
root = root.left
57+
58+
root = stack.pop()
59+
60+
# 이전 값보닀 μž‘κ±°λ‚˜ κ°™μœΌλ©΄ BST μœ„λ°˜
61+
if prev is not None and root.val <= prev:
62+
return False
63+
prev = root.val
64+
65+
# 였λ₯Έμͺ½μœΌλ‘œ 이동
66+
root = root.right
67+
68+
return True
69+
70+
171
# O(n) time, O(n) space
272

373
# Definition for a binary tree node.

0 commit comments

Comments
Β (0)