Skip to content

Commit 1204757

Browse files
authoredMar 15, 2025
Merge pull request #1099 from dusunax/main
[SunaDu] Week 14
·
v4.11.0v3.14.0
2 parents 9c2c64f + f2d9bfc commit 1204757

File tree

5 files changed

+232
-3
lines changed

5 files changed

+232
-3
lines changed
 
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
'''
2+
# Leetcode 102. Binary Tree Level Order Traversal
3+
4+
do level order traversal
5+
6+
```
7+
💡 why use BFS?:
8+
BFS is the recommended approach, because it aligns with the problem's concept of processing the binary tree level by level and avoids issues related to recursion depth, making the solution both cleaner and more reliable.
9+
10+
- DFS doesn't naturally support level-by-level traversal, so we need an extra variable like "dep" (depth).
11+
- BFS is naturally designed for level traversal, making it a better fit for the problem.
12+
- additionally, BFS can avoid potential stack overflow.
13+
```
14+
15+
## A. BFS
16+
17+
### re-structuring the tree into a queue:
18+
- use the queue for traverse the binary tree by level.
19+
20+
### level traversal:
21+
- pop the leftmost node
22+
- append the node's value to current level's array
23+
- enqueue the left and right children to queue
24+
- can only process nodes at the current level, because of level_size.
25+
26+
## B. DFS
27+
- travase with a dep parameter => dp(node, dep)
28+
- store the traversal result
29+
'''
30+
class Solution:
31+
'''
32+
A. BFS
33+
TC: O(n)
34+
SC: O(n)
35+
'''
36+
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
37+
if not root:
38+
return []
39+
40+
result = [] # SC: O(n)
41+
queue = deque([root]) # SC: O(n)
42+
43+
while queue: # TC: O(n)
44+
level_size = len(queue)
45+
level = []
46+
47+
for _ in range(level_size):
48+
node = queue.popleft()
49+
level.append(node.val)
50+
51+
if node.left:
52+
queue.append(node.left)
53+
if node.right:
54+
queue.append(node.right)
55+
56+
result.append(level)
57+
58+
return result
59+
60+
'''
61+
B. DFS
62+
TC: O(n)
63+
SC: O(n)
64+
'''
65+
def levelOrderDP(self, root: Optional[TreeNode]) -> List[List[int]]:
66+
result = [] # SC: O(n)
67+
68+
def dp(node, dep):
69+
if node is None:
70+
return
71+
72+
if len(result) <= dep:
73+
result.append([])
74+
75+
result[dep].append(node.val)
76+
77+
dp(node.left, dep + 1)
78+
dp(node.right, dep + 1)
79+
80+
dp(root, 0) # TC: O(n) call stack
81+
82+
return result

‎counting-bits/dusunax.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
'''
2+
# 338. Counting Bits
3+
4+
0부터 n까지의 이진수에서 1의 개수 세기
5+
6+
## 풀이A. 브루투포스
7+
- 전부 계산하기
8+
9+
## 풀이B. DP
10+
```
11+
이진수 = (이진수 >> 1) + (이진수 & 1)
12+
```
13+
- `i >> 1`: i의 비트를 오른쪽으로 1비트 이동(맨 오른쪽 한 칸 버림), `i // 2`와 같음
14+
- `i & 1`: `i`의 마지막 비트가 1인지 확인 (1이면 1 추가, 0이면 패스)
15+
- DP 테이블에서 이전 계산(i >> 1) 결과를 가져와서 현재 계산(i & 1) 결과를 더한다.
16+
'''
17+
class Solution:
18+
'''
19+
A. brute force
20+
SC: O(n log n)
21+
TC: O(n)
22+
'''
23+
def countBitsBF(self, n: int) -> List[int]:
24+
result = []
25+
26+
for i in range(n + 1): # TC: O(n)
27+
result.append(bin(i).count('1')) # TC: O(log n)
28+
29+
return result
30+
31+
'''
32+
B. DP
33+
SC: O(n)
34+
TC: O(n)
35+
'''
36+
def countBits(self, n: int) -> List[int]:
37+
dp = [0] * (n + 1)
38+
39+
for i in range(1, n + 1): # TC: O(n)
40+
dp[i] = dp[i >> 1] + (i & 1) # TC: O(1)
41+
42+
return dp

‎house-robber-ii/dusunax.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
'''
2+
# 213. House Robber II
3+
4+
house roober 1 + circular array
5+
6+
## Solution
7+
solve by using two cases:
8+
- robbing from the first house to the last house
9+
- robbing from the second house to the last house
10+
'''
11+
class Solution:
12+
'''
13+
A. pass indices to function
14+
TC: O(n)
15+
SC: O(1)
16+
'''
17+
def rob(self, nums: Lit[int]) -> int:
18+
if len(nums) == 1:
19+
return nums[0]
20+
21+
def robbing(start, end):
22+
prev, maxAmount = 0, 0
23+
24+
for i in range(start, end):
25+
prev, maxAmount = maxAmount, max(maxAmount, prev + nums[i])
26+
27+
return maxAmount
28+
29+
return max(robbing(0, len(nums) - 1), robbing(1, len(nums)))
30+
31+
'''
32+
B. pass list to function
33+
TC: O(n)
34+
SC: O(n) (list slicing)
35+
'''
36+
def robWithSlicing(self, nums: List[int]) -> int:
37+
if len(nums) == 1:
38+
return nums[0]
39+
40+
def robbing(nums):
41+
prev, maxAmount = 0, 0
42+
43+
for num in nums:
44+
prev, maxAmount = maxAmount, max(maxAmount, prev + num)
45+
46+
return maxAmount
47+
48+
return max(robbing(nums[1:]), robbing(nums[:-1]))

‎meeting-rooms-ii/dusunax.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
'''
2+
# 253. Meeting Rooms II
3+
4+
최소 힙 Min Heap을 사용하여 회의 종료 시간을 저장합니다. 최소 힙의 길이는 필요한 회의실 개수입니다.
5+
6+
## 개념
7+
```
8+
💡 최소 힙 Min Heap
9+
- 힙은 완전 이진 트리이다.
10+
- 부모 노드의 값이 자식 노드의 값보다 작다.
11+
- 최소값을 루트에 두기 때문에 최소값을 찾는 시간복잡도가 O(1)이다.
12+
```
13+
```
14+
💡 완전 이진 트리
15+
- 트리의 모든 레벨이 완전히 채워져 있고, 마지막 레벨은 왼쪽부터 채운다.
16+
- 삽입과 삭제는 O(log n)의 시간복잡도를 가진다.
17+
- 삽입은 트리의 마지막 노드에 삽입하고 버블업을 진행한다.
18+
- 삭제는 트리의 루트 노드를 삭제하고, 버블다운을 진행한다.
19+
```
20+
21+
## 회의실 재사용 조건
22+
가장 먼저 끝나는 회의와 다음 회의 시작을 비교하여, 다음 회의 시작이 가장 먼저 끝나는 회의보다 크거나 같다면, 같은 회의실을 사용 가능하다.
23+
24+
## 풀이
25+
```
26+
최소 힙의 길이 = 사용 중인 회의실 개수 = 필요한 회의실 개수
27+
```
28+
1. 회의 시작 시간을 기준으로 정렬
29+
2. 회의 배열을 순회하며 회의 종료 시간을 최소 힙에 저장
30+
3. 회의실을 재사용할 수 있는 경우, 가장 먼저 끝나는 회의 삭제 후 새 회의 종료 시간 추가(해당 회의실의 종료 시간 업데이트)
31+
4. 최종 사용 중인 회의실 개수를 반환
32+
33+
## 시간 & 공간 복잡도
34+
35+
### TC is O(n log n)
36+
- 회의 배열 정렬: O(n log n)
37+
- 회의 배열 순회: O(n)
38+
- 최소 힙 삽입 & 삭제: O(log n)
39+
40+
### SC is O(n)
41+
- 최소 힙: 최악의 경우 O(n)
42+
'''
43+
from heapq import heappush, heappop
44+
45+
class Solution:
46+
def minMeetingRooms(self, intervals: List[Interval]) -> int:
47+
if not intervals:
48+
return 0
49+
50+
intervals.sort(key=lambda x: x.start)
51+
52+
min_heap = []
53+
for interval in intervals:
54+
if min_heap and min_heap[0] <= interval.start:
55+
heappop(min_heap)
56+
57+
heappush(min_heap, interval.end)
58+
59+
return len(min_heap)

‎meeting-rooms/dusunax.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,18 @@
66
- 회의 시간이 겹치지 않는 경우 회의를 진행할 수 있다.
77
88
## 풀이
9-
109
- intervals를 시작 시간으로 정렬한다.
1110
- 시간 겹침 여부를 확인한다.
1211
- 겹치는 경우 False, 겹치지 않는 경우 True를 반환한다.
1312
14-
## 시간 복잡도
13+
## 시간 & 공간 복잡도
1514
1615
### TC is O(n log n)
1716
- 정렬 시간: O(n log n)
1817
- 겹침 여부 확인 시간: O(n)
1918
2019
### SC is O(1)
2120
- 추가 사용 공간 없음
22-
2321
'''
2422
class Solution:
2523
def canAttendMeetings(self, intervals: List[List[int]]) -> bool:

0 commit comments

Comments
 (0)
Please sign in to comment.