Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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]))