Skip to content
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
49 changes: 49 additions & 0 deletions find-median-from-data-stream/yuseok89.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🏷️ 알고리즘 패턴 분석

find-median-from-data-stream/yuseok89.py
# TC (NlogN)
# SC (N)
class MedianFinder:

    def __init__(self):
        self.max_heap = []
        self.min_heap = []

    def addNum(self, num: int) -> None:
        if len(self.min_heap) == 0 and len(self.max_heap) == 0:
            heapq.heappush(self.min_heap, num)
        elif len(self.max_heap) == 0:
            mid = heapq.heappop(self.min_heap)
            heapq.heappush(self.max_heap, -min(mid, num))
            heapq.heappush(self.min_heap, max(mid, num))
        elif len(self.max_heap) == len(self.min_heap):
            mid1 = -self.max_heap[0]
            mid2 = self.min_heap[0]

            if num <= mid1:
                heapq.heappush(self.max_heap, -num)
            else:
                heapq.heappush(self.min_heap, num)
        else:
            if len(self.max_heap) > len(self.min_heap):
                mid = -heapq.heappop(self.max_heap)
            else:
                mid = heapq.heappop(self.min_heap)

            heapq.heappush(self.max_heap, -min(mid, num))
            heapq.heappush(self.min_heap, max(mid, num))

    def findMedian(self) -> float:
        if len(self.max_heap) == len(self.min_heap):
            mid1 = -self.max_heap[0]
            mid2 = self.min_heap[0]
            return (mid1 + mid2) / 2.0
        else:
            if len(self.max_heap) > len(self.min_heap):
                return float(-self.max_heap[0])
            else:
                return float(self.min_heap[0])


# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()
  • 패턴: Heap / Priority Queue, Two Pointers, Hash Map / Hash Set
  • 설명: 데이터를 둘 다 힙으로 분리해 중앙값을 유지하는 구조로, 최대힙/최소힙을 번갈아 활용하여 중앙값에 접근하는 방식이다. 일반적으로 힙 기반으로 실시간으로 중간값을 구하는 문제에서 사용된다.

📊 시간/공간 복잡도 분석

복잡도
Time O(log n)
Space O(n)

피드백: 두 개의 힙을 유지하며 삽입 시 균형을 유지해 중앙값을 구한다. 각 연산은 힙 원소 재배열로 로그 시간 복잡도를 가진다.

개선 제안: 현재 구현이 적절해 보입니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# TC (NlogN)
# SC (N)
class MedianFinder:

def __init__(self):
self.max_heap = []
self.min_heap = []

def addNum(self, num: int) -> None:
if len(self.min_heap) == 0 and len(self.max_heap) == 0:
heapq.heappush(self.min_heap, num)
elif len(self.max_heap) == 0:
mid = heapq.heappop(self.min_heap)
heapq.heappush(self.max_heap, -min(mid, num))
heapq.heappush(self.min_heap, max(mid, num))
elif len(self.max_heap) == len(self.min_heap):
mid1 = -self.max_heap[0]
mid2 = self.min_heap[0]

if num <= mid1:
heapq.heappush(self.max_heap, -num)
else:
heapq.heappush(self.min_heap, num)
else:
if len(self.max_heap) > len(self.min_heap):
mid = -heapq.heappop(self.max_heap)
else:
mid = heapq.heappop(self.min_heap)

heapq.heappush(self.max_heap, -min(mid, num))
heapq.heappush(self.min_heap, max(mid, num))

def findMedian(self) -> float:
if len(self.max_heap) == len(self.min_heap):
mid1 = -self.max_heap[0]
mid2 = self.min_heap[0]
return (mid1 + mid2) / 2.0
else:
if len(self.max_heap) > len(self.min_heap):
return float(-self.max_heap[0])
else:
return float(self.min_heap[0])


# Your MedianFinder object will be instantiated and called as such:
# obj = MedianFinder()
# obj.addNum(num)
# param_2 = obj.findMedian()

24 changes: 24 additions & 0 deletions insert-interval/yuseok89.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🏷️ 알고리즘 패턴 분석

insert-interval/yuseok89.py
#TD: O(1)
#SC: O(2)
class Solution:
    def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:

        ans = []
        is_processed = False

        for interval in intervals:
            if is_processed or interval[1] < newInterval[0]:
                ans.append(interval)
            elif newInterval[1] < interval[0]:
                ans.append(newInterval)
                ans.append(interval)
                is_processed = True
            else:
                newInterval[0] = min(newInterval[0], interval[0])
                newInterval[1] = max(newInterval[1], interval[1])

        if not ans or ans[-1][1] < newInterval[0]:
            ans.append(newInterval)

        return ans
  • 패턴: Two Pointers, Greedy, Binary Search
  • 설명: 두 구간 배열에서 새 구간을 삽입하며 겹치는 구간을 합치는 과정에서 포인터처럼 순회를 이용해 범위를 확장/결합하는 패턴이 드러납니다. 간단히 말해 범위 겹침 처리와 기준 위치 탐색으로 Greedy 성격도 보이고, 이분 탐색 없이 선형 탐색으로 해결하는 구조입니다.

📊 시간/공간 복잡도 분석

유저 분석 실제 분석 결과
Time - O(n) -
Space O(2) O(n)

피드백: 한 번의 순회로 중복 구간을 병합하며 결과 배열을 구성한다. 입력이 이미 정렬되어 있을 때 효율적이다.

개선 제안: 현재 구현이 적절해 보입니다.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🏷️ 알고리즘 패턴 분석

insert-interval/yuseok89.py
#TC: O(1)
#SC: O(2)
class Solution:
    def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:

        ans = []
        is_processed = False

        for interval in intervals:
            if is_processed or interval[1] < newInterval[0]:
                ans.append(interval)
            elif newInterval[1] < interval[0]:
                ans.append(newInterval)
                ans.append(interval)
                is_processed = True
            else:
                newInterval[0] = min(newInterval[0], interval[0])
                newInterval[1] = max(newInterval[1], interval[1])

        if not ans or ans[-1][1] < newInterval[0]:
            ans.append(newInterval)

        return ans
  • 패턴: Two Pointers, Greedy, Binary Search, Dynamic Programming, Backtracking, Divide and Conquer, Hash Map / Hash Set, Sliding Window, DFS, BFS, Union Find, Trie, Bit Manipulation, Heap / Priority Queue, Monotonic Stack
  • 설명: 주요 로직은 기존 구간들과 새 구간의 관계를 차례대로 비교하며 병합 여부를 판단하고, 필요한 경우 새 구간의 경계를 확장하는 방식이다. 선형 스캔으로 구간을 처리하는 패턴으로 Two Pointers/Greedy에 해당한다.

📊 시간/공간 복잡도 분석

유저 분석 실제 분석 결과
Time O(1) O(n)
Space O(2) O(n)

피드백: 정렬된 구간 리스트를 가정하고, 겹치지 않는 경우와 겹치는 경우를 나눠 처리한다. 새로운 구간과 기존 구간의 합치는 과정이 한 번의 순회로 끝난다.

개선 제안: 현재 구현이 적절해 보입니다.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🏷️ 알고리즘 패턴 분석

insert-interval/yuseok89.py
#TC: O(N)
#SC: O(N)
class Solution:
    def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:

        ans = []
        is_processed = False

        for interval in intervals:
            if is_processed or interval[1] < newInterval[0]:
                ans.append(interval)
            elif newInterval[1] < interval[0]:
                ans.append(newInterval)
                ans.append(interval)
                is_processed = True
            else:
                newInterval[0] = min(newInterval[0], interval[0])
                newInterval[1] = max(newInterval[1], interval[1])

        if not ans or ans[-1][1] < newInterval[0]:
            ans.append(newInterval)

        return ans
  • 패턴: Two Pointers, Greedy, Dynamic Programming
  • 설명: 주어진 코드는 여러 구간을 순회하며 새로운 구간과의 겹침 여부를 확인하고 합치는 과정을 통해 정렬된 구간 목록을 구성합니다. 각 구간 비교로 필요한 경우 합치고, 그렇지 않으면 현재 구간을 결과에 추가하는 흐름이 그리디 성격을 띄며, 투 포인터 스타일의 순차 처리와 구간 합치기 로직이 핵심입니다.

📊 시간/공간 복잡도 분석

유저 분석 실제 분석 결과
Time O(N) O(n)
Space O(N) O(n)

피드백: 모든 구간을 한 번의 순회로 처리하며 필요 시 새 구간과 기존 구간의 병합 결과를 업데이트합니다. 보조 리스트에 최종 결과를 저장합니다.

개선 제안: 현재 구현이 적절해 보입니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#TC: O(N)
#SC: O(N)
class Solution:
def insert(self, intervals: list[list[int]], newInterval: list[int]) -> list[list[int]]:

ans = []
is_processed = False

for interval in intervals:
if is_processed or interval[1] < newInterval[0]:
ans.append(interval)
elif newInterval[1] < interval[0]:
ans.append(newInterval)
ans.append(interval)
is_processed = True
else:
newInterval[0] = min(newInterval[0], interval[0])
newInterval[1] = max(newInterval[1], interval[1])

if not ans or ans[-1][1] < newInterval[0]:
ans.append(newInterval)

return ans

32 changes: 32 additions & 0 deletions kth-smallest-element-in-a-bst/yuseok89.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🏷️ 알고리즘 패턴 분석

kth-smallest-element-in-a-bst/yuseok89.py
# TC: O(N)
# SC: O(1)
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def kthSmallest(self, root: TreeNode | None, k: int) -> int:

        ans = 0

        def rec(node: TreeNode | None) -> None:
            nonlocal k, ans

            if node is None or k <= 0:
                return

            rec(node.left)

            k -= 1
            if k == 0:
                ans = node.val
                return

            rec(node.right)

        rec(root)

        return ans
  • 패턴: Binary Search, DFS
  • 설명: 중위 순회로 이진 BST를 방문하며 순서를 세는 방식으로 k번째 원소를 찾는 DFS 기반 풀이이며, 좌우 자식 방문 순서를 활용해 BST의 특징을 이용합니다.

📊 시간/공간 복잡도 분석

유저 분석 실제 분석 결과
Time O(N) O(n)
Space O(1) O(n)

피드백: Left-Root-Right 순회로 정확히 k번째 노드를 찾도록 구현했다. 재귀 깊이에 따라 공간 복잡도가 좌우된다.

개선 제안: 재귀 대신 반복 방문으로 스택 사용을 명확히 관리하면 공간 예측이 쉬워진다.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🏷️ 알고리즘 패턴 분석

kth-smallest-element-in-a-bst/yuseok89.py
# TC: O(N)
# SC: O(H)
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def kthSmallest(self, root: TreeNode | None, k: int) -> int:

        ans = 0

        def rec(node: TreeNode | None) -> None:
            nonlocal k, ans

            if node is None or k <= 0:
                return

            rec(node.left)

            k -= 1
            if k == 0:
                ans = node.val
                return

            rec(node.right)

        rec(root)

        return ans
  • 패턴: Binary Search, Depth-First Search, Backtracking
  • 설명: 이 코드는 이진 트리에서 중위 순회를 재귀적으로 수행하여 k번째 노드를 찾는다. 좌측 자식 먼저 방문하는 DFS(깊이 우선 탐색)와 k 카운트를 활용한 탐색 중단으로 문제를 해결한다.

📊 시간/공간 복잡도 분석

유저 분석 실제 분석 결과
Time O(N) O(n)
Space O(H) O(h)

피드백: 왼쪽 자식부터 방문하고 방문한 순서를 카운트하여 k번째 노드를 찾습니다. 재귀 깊이는 트리의 높이와 같습니다.

개선 제안: 현재 구현이 적절해 보입니다.

Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# TC: O(N)
# SC: O(H)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def kthSmallest(self, root: TreeNode | None, k: int) -> int:

ans = 0

def rec(node: TreeNode | None) -> None:
nonlocal k, ans

if node is None or k <= 0:
return

rec(node.left)

k -= 1
if k == 0:
ans = node.val
return

rec(node.right)

rec(root)

return ans

18 changes: 18 additions & 0 deletions lowest-common-ancestor-of-a-binary-search-tree/yuseok89.py

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🏷️ 알고리즘 패턴 분석

lowest-common-ancestor-of-a-binary-search-tree/yuseok89.py
# TC: O(H)
# SC: O(1)
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if root.val < p.val and root.val < q.val:
            return self.lowestCommonAncestor(root.right, p, q)
        elif root.val > p.val and root.val > q.val:
            return self.lowestCommonAncestor(root.left, p, q)
        else:
            return root
  • 패턴: Binary Search, Divide and Conquer
  • 설명: BST의 특성을 이용해 중간 값을 찾지 않고, p와 q의 값으로 루트와 비교해 탐색 방향을 결정하는 패턴으로 부분 문제를 재귀적으로 해결하는 Divide and Conquer 방식입니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(h)
Space O(1)

피드백: BST의 특성을 이용해 루트와 노드 값의 대소 비교만으로 LCA를 찾는 간단한 재귀 풀이이다.

개선 제안: 현재 구현이 적절해 보입니다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🏷️ 알고리즘 패턴 분석

lowest-common-ancestor-of-a-binary-search-tree/yuseok89.py
# TC: O(H)
# SC: O(H)
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if root.val < p.val and root.val < q.val:
            return self.lowestCommonAncestor(root.right, p, q)
        elif root.val > p.val and root.val > q.val:
            return self.lowestCommonAncestor(root.left, p, q)
        else:
            return root
  • 패턴: Binary Search, Divide and Conquer
  • 설명: BST의 특징을 이용해 루트와 두 노드의 값 비교로 탐색 방향을 결정하고, 재귀적으로 LCA를 찾는 방식으로 문제를 해결하므로 Binary Search 패턴과 Divide and Conquer 패턴에 해당합니다.

📊 시간/공간 복잡도 분석

복잡도
Time O(h)
Space O(h)

피드백: BST의 성질: 두 노드의 값이 서로 다른 방향으로 배열되면 그 노드가 LCA이다. 재귀적으로 최적 경로로 내려간다.

개선 제안: 재귀 깊이가 커질 경우 스택 오버플로를 주의하고, 반복 방식으로 구현해도 된다.

💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!

Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# TC: O(H)
# SC: O(H)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root.val < p.val and root.val < q.val:
return self.lowestCommonAncestor(root.right, p, q)
elif root.val > p.val and root.val > q.val:
return self.lowestCommonAncestor(root.left, p, q)
else:
return root

Loading