From 6b44cccb0b9217043924eb3d016da462c590c66f Mon Sep 17 00:00:00 2001 From: Dusuna <94776135+dusunax@users.noreply.github.com> Date: Wed, 12 Mar 2025 17:53:00 +0900 Subject: [PATCH 1/5] add solution: counting-bits --- counting-bits/dusunax.py | 42 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 counting-bits/dusunax.py diff --git a/counting-bits/dusunax.py b/counting-bits/dusunax.py new file mode 100644 index 000000000..eb98a98e7 --- /dev/null +++ b/counting-bits/dusunax.py @@ -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 From ff631d5a5e1c5c8f480a58c7162328af2c397496 Mon Sep 17 00:00:00 2001 From: Dusuna <94776135+dusunax@users.noreply.github.com> Date: Thu, 13 Mar 2025 22:17:01 +0900 Subject: [PATCH 2/5] add solution: binary-tree-level-order-traversal --- binary-tree-level-order-traversal/dusunax.py | 82 ++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 binary-tree-level-order-traversal/dusunax.py diff --git a/binary-tree-level-order-traversal/dusunax.py b/binary-tree-level-order-traversal/dusunax.py new file mode 100644 index 000000000..02a579187 --- /dev/null +++ b/binary-tree-level-order-traversal/dusunax.py @@ -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) + 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 From 3d974267c810e08a4659a78cd04edc6d5720b5f2 Mon Sep 17 00:00:00 2001 From: Dusuna <94776135+dusunax@users.noreply.github.com> Date: Fri, 14 Mar 2025 02:46:05 +0900 Subject: [PATCH 3/5] add solution: house-robber-ii --- house-robber-ii/dusunax.py | 48 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 house-robber-ii/dusunax.py diff --git a/house-robber-ii/dusunax.py b/house-robber-ii/dusunax.py new file mode 100644 index 000000000..a936c10c1 --- /dev/null +++ b/house-robber-ii/dusunax.py @@ -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 + + 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])) From 707b50c71a31388fa53655e3fc9c47d95451c26a Mon Sep 17 00:00:00 2001 From: Dusuna <94776135+dusunax@users.noreply.github.com> Date: Sat, 15 Mar 2025 16:41:07 +0900 Subject: [PATCH 4/5] add solution: meeting-rooms-ii --- meeting-rooms-ii/dusunax.py | 58 +++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 meeting-rooms-ii/dusunax.py diff --git a/meeting-rooms-ii/dusunax.py b/meeting-rooms-ii/dusunax.py new file mode 100644 index 000000000..8b21bff53 --- /dev/null +++ b/meeting-rooms-ii/dusunax.py @@ -0,0 +1,58 @@ +''' +# 253. Meeting Rooms II + +최소 힙 Min Heap을 사용하여 회의 종료 시간을 저장합니다. 최소 힙의 길이는 필요한 회의실 개수입니다. + +## 개념 +``` +💡 최소 힙 Min Heap +- 힙은 완전 이진 트리이다. +- 부모 노드의 값이 자식 노드의 값보다 작다. +- 최소값을 루트에 두기 때문에 최소값을 찾는 시간복잡도가 O(1)이다. +``` +``` +💡 완전 이진 트리 +- 트리의 모든 레벨이 완전히 채워져 있고, 마지막 레벨은 왼쪽부터 채운다. +- 삽입과 삭제는 O(log n)의 시간복잡도를 가진다. + - 삽입은 트리의 마지막 노드에 삽입하고 버블업을 진행한다. + - 삭제는 트리의 루트 노드를 삭제하고, 버블다운을 진행한다. +``` + +## 회의실 재사용 조건 +가장 먼저 끝나는 회의와 다음 회의 시작을 비교하여, 다음 회의 시작이 가장 먼저 끝나는 회의보다 크거나 같다면, 같은 회의실을 사용 가능하다. + +## 풀이 +``` +최소 힙의 길이 = 사용 중인 회의실 개수 = 필요한 회의실 개수 +``` +1. 회의 시작 시간을 기준으로 정렬 +2. 회의 배열을 순회하며 회의 종료 시간을 최소 힙에 저장 +3. 회의실을 재사용할 수 있는 경우, 가장 먼저 끝나는 회의 삭제 후 새 회의 종료 시간 추가(해당 회의실의 종료 시간 업데이트) +4. 최종 사용 중인 회의실 개수를 반환 + + +## 시간 & 공간 복잡도 +- 시간 복잡도: O(n log n) + - 회의 배열 정렬: O(n log n) + - 회의 배열 순회: O(n) + - 최소 힙 삽입 & 삭제: O(log n) +- 공간 복잡도: 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) From f2d9bfc645b68b15c0d607655748ae298524fa03 Mon Sep 17 00:00:00 2001 From: Dusuna <94776135+dusunax@users.noreply.github.com> Date: Sat, 15 Mar 2025 16:46:07 +0900 Subject: [PATCH 5/5] update solution: update comments on meeting-rooms & meeting-rooms-ii --- meeting-rooms-ii/dusunax.py | 15 ++++++++------- meeting-rooms/dusunax.py | 4 +--- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/meeting-rooms-ii/dusunax.py b/meeting-rooms-ii/dusunax.py index 8b21bff53..3fd4bc4d4 100644 --- a/meeting-rooms-ii/dusunax.py +++ b/meeting-rooms-ii/dusunax.py @@ -30,14 +30,15 @@ 3. 회의실을 재사용할 수 있는 경우, 가장 먼저 끝나는 회의 삭제 후 새 회의 종료 시간 추가(해당 회의실의 종료 시간 업데이트) 4. 최종 사용 중인 회의실 개수를 반환 - ## 시간 & 공간 복잡도 -- 시간 복잡도: O(n log n) - - 회의 배열 정렬: O(n log n) - - 회의 배열 순회: O(n) - - 최소 힙 삽입 & 삭제: O(log n) -- 공간 복잡도: O(n) - - 최소 힙 사용: O(n), 최악의 경우 + +### 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 diff --git a/meeting-rooms/dusunax.py b/meeting-rooms/dusunax.py index 28f2407c2..618802711 100644 --- a/meeting-rooms/dusunax.py +++ b/meeting-rooms/dusunax.py @@ -6,12 +6,11 @@ - 회의 시간이 겹치지 않는 경우 회의를 진행할 수 있다. ## 풀이 - - intervals를 시작 시간으로 정렬한다. - 시간 겹침 여부를 확인한다. - 겹치는 경우 False, 겹치지 않는 경우 True를 반환한다. -## 시간 복잡도 +## 시간 & 공간 복잡도 ### TC is O(n log n) - 정렬 시간: O(n log n) @@ -19,7 +18,6 @@ ### SC is O(1) - 추가 사용 공간 없음 - ''' class Solution: def canAttendMeetings(self, intervals: List[List[int]]) -> bool: