Skip to content

[SunaDu] Week 14 #1099

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Mar 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions binary-tree-level-order-traversal/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
'''
# Leetcode 102. Binary Tree Level Order Traversal

do level order traversal

```
💡 why use BFS?:
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.

- DFS doesn't naturally support level-by-level traversal, so we need an extra variable like "dep" (depth).
- BFS is naturally designed for level traversal, making it a better fit for the problem.
- additionally, BFS can avoid potential stack overflow.
```

## A. BFS

### re-structuring the tree into a queue:
- use the queue for traverse the binary tree by level.

### level traversal:
- pop the leftmost node
- append the node's value to current level's array
- enqueue the left and right children to queue
- can only process nodes at the current level, because of level_size.

## B. DFS
- travase with a dep parameter => dp(node, dep)
- store the traversal result
'''
class Solution:
'''
A. BFS
TC: O(n)
SC: O(n)
'''
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []

result = [] # SC: O(n)
queue = deque([root]) # SC: O(n)

while queue: # TC: O(n)
level_size = len(queue)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오 같은 레벨을 이런 식으로 관리할 수도 있군요! 하나 배워 갑니다.

level = []

for _ in range(level_size):
node = queue.popleft()
level.append(node.val)

if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)

result.append(level)

return result

'''
B. DFS
TC: O(n)
SC: O(n)
'''
def levelOrderDP(self, root: Optional[TreeNode]) -> List[List[int]]:
result = [] # SC: O(n)

def dp(node, dep):
if node is None:
return

if len(result) <= dep:
result.append([])

result[dep].append(node.val)

dp(node.left, dep + 1)
dp(node.right, dep + 1)

dp(root, 0) # TC: O(n) call stack

return result
42 changes: 42 additions & 0 deletions counting-bits/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
'''
# 338. Counting Bits

0부터 n까지의 이진수에서 1의 개수 세기

## 풀이A. 브루투포스
- 전부 계산하기

## 풀이B. DP
```
이진수 = (이진수 >> 1) + (이진수 & 1)
```
- `i >> 1`: i의 비트를 오른쪽으로 1비트 이동(맨 오른쪽 한 칸 버림), `i // 2`와 같음
- `i & 1`: `i`의 마지막 비트가 1인지 확인 (1이면 1 추가, 0이면 패스)
- DP 테이블에서 이전 계산(i >> 1) 결과를 가져와서 현재 계산(i & 1) 결과를 더한다.
'''
class Solution:
'''
A. brute force
SC: O(n log n)
TC: O(n)
'''
def countBitsBF(self, n: int) -> List[int]:
result = []

for i in range(n + 1): # TC: O(n)
result.append(bin(i).count('1')) # TC: O(log n)

return result

'''
B. DP
SC: O(n)
TC: O(n)
'''
def countBits(self, n: int) -> List[int]:
dp = [0] * (n + 1)

for i in range(1, n + 1): # TC: O(n)
dp[i] = dp[i >> 1] + (i & 1) # TC: O(1)

return dp
48 changes: 48 additions & 0 deletions house-robber-ii/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
'''
# 213. House Robber II

house roober 1 + circular array

## Solution
solve by using two cases:
- robbing from the first house to the last house
- robbing from the second house to the last house
'''
class Solution:
'''
A. pass indices to function
TC: O(n)
SC: O(1)
'''
def rob(self, nums: Lit[int]) -> int:
if len(nums) == 1:
return nums[0]

def robbing(start, end):
prev, maxAmount = 0, 0
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오 이런식으로 공간 최적화도 할 수 있군요!

Copy link
Member Author

@dusunax dusunax Mar 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

문제를 풀거나 막힌 뒤에 알고달레 풀이와 Leetcode Solutions 탭을 보면서 정리하는 과정이 도움이 많이 되었어요. 공간 최적화도 이 방법으로 진행했습니다!


for i in range(start, end):
prev, maxAmount = maxAmount, max(maxAmount, prev + nums[i])

return maxAmount

return max(robbing(0, len(nums) - 1), robbing(1, len(nums)))

'''
B. pass list to function
TC: O(n)
SC: O(n) (list slicing)
'''
def robWithSlicing(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0]

def robbing(nums):
prev, maxAmount = 0, 0

for num in nums:
prev, maxAmount = maxAmount, max(maxAmount, prev + num)

return maxAmount

return max(robbing(nums[1:]), robbing(nums[:-1]))
59 changes: 59 additions & 0 deletions meeting-rooms-ii/dusunax.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
'''
# 253. Meeting Rooms II

최소 힙 Min Heap을 사용하여 회의 종료 시간을 저장합니다. 최소 힙의 길이는 필요한 회의실 개수입니다.

## 개념
```
💡 최소 힙 Min Heap
- 힙은 완전 이진 트리이다.
- 부모 노드의 값이 자식 노드의 값보다 작다.
- 최소값을 루트에 두기 때문에 최소값을 찾는 시간복잡도가 O(1)이다.
```
```
💡 완전 이진 트리
- 트리의 모든 레벨이 완전히 채워져 있고, 마지막 레벨은 왼쪽부터 채운다.
- 삽입과 삭제는 O(log n)의 시간복잡도를 가진다.
- 삽입은 트리의 마지막 노드에 삽입하고 버블업을 진행한다.
- 삭제는 트리의 루트 노드를 삭제하고, 버블다운을 진행한다.
```

## 회의실 재사용 조건
가장 먼저 끝나는 회의와 다음 회의 시작을 비교하여, 다음 회의 시작이 가장 먼저 끝나는 회의보다 크거나 같다면, 같은 회의실을 사용 가능하다.

## 풀이
```
최소 힙의 길이 = 사용 중인 회의실 개수 = 필요한 회의실 개수
```
1. 회의 시작 시간을 기준으로 정렬
2. 회의 배열을 순회하며 회의 종료 시간을 최소 힙에 저장
3. 회의실을 재사용할 수 있는 경우, 가장 먼저 끝나는 회의 삭제 후 새 회의 종료 시간 추가(해당 회의실의 종료 시간 업데이트)
4. 최종 사용 중인 회의실 개수를 반환

## 시간 & 공간 복잡도

### TC is O(n log n)
- 회의 배열 정렬: O(n log n)
- 회의 배열 순회: O(n)
- 최소 힙 삽입 & 삭제: O(log n)

### SC is O(n)
- 최소 힙: 최악의 경우 O(n)
'''
from heapq import heappush, heappop

class Solution:
def minMeetingRooms(self, intervals: List[Interval]) -> int:
if not intervals:
return 0

intervals.sort(key=lambda x: x.start)

min_heap = []
for interval in intervals:
if min_heap and min_heap[0] <= interval.start:
heappop(min_heap)

heappush(min_heap, interval.end)

return len(min_heap)
4 changes: 1 addition & 3 deletions meeting-rooms/dusunax.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,18 @@
- 회의 시간이 겹치지 않는 경우 회의를 진행할 수 있다.

## 풀이

- intervals를 시작 시간으로 정렬한다.
- 시간 겹침 여부를 확인한다.
- 겹치는 경우 False, 겹치지 않는 경우 True를 반환한다.

## 시간 복잡도
## 시간 & 공간 복잡도

### TC is O(n log n)
- 정렬 시간: O(n log n)
- 겹침 여부 확인 시간: O(n)

### SC is O(1)
- 추가 사용 공간 없음

'''
class Solution:
def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
Expand Down