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
43 changes: 43 additions & 0 deletions alien-dictionary/dolphinflow86.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.

🏷️ 알고리즘 패턴 분석

alien-dictionary/dolphinflow86.py
# C is total length of all words, U is number of unique alien letters (<= 26).
# TC: O(C) - comparing adjacent words and processing topological sort graph
# SC: O(1) - unique letters and adjacency list bounded by 26 characters

from collections import deque


class Solution:

    def alienOrder(self, words) -> str:
        adj = {char: set() for word in words for char in word}
        indegree = {char: 0 for word in words for char in word}

        for i in range(len(words) - 1):
            w1, w2 = words[i], words[i + 1]
            min_len = min(len(w1), len(w2))

            if len(w1) > len(w2) and w1[:min_len] == w2[:min_len]:
                return ""

            for j in range(min_len):
                if w1[j] != w2[j]:
                    if w2[j] not in adj[w1[j]]:
                        adj[w1[j]].add(w2[j])
                        indegree[w2[j]] += 1
                    break

        queue = deque([char for char in indegree if indegree[char] == 0])
        result = []

        while queue:
            char = queue.popleft()
            result.append(char)

            for neighbor in adj[char]:
                indegree[neighbor] -= 1
                if indegree[neighbor] == 0:
                    queue.append(neighbor)

        if len(result) < len(indegree):
            return ""

        return "".join(result)
  • 패턴: Topological Sort, Hash Map / Hash Set, Breadth-First Search
  • 설명: 주어진 코드는 알파벳 간 선후관계를 그래프로 표현하고 위상 정렬을 통해 순서를 구한다. 또한 인접 리스트와 indegree를 이용해 간선과 노드를 관리하므로 해시 맵/세트를 사용하며 BFS 스타일의 큐를 이용한 탐색으로 위상정렬을 구현한다.

📊 시간/공간 복잡도 분석

복잡도
Time O(N + E)
Space O(U + E)

피드백: 그래프를 구성하고 위상 정렬(큐 기반 BFS)을 수행하여 결과 문자열을 얻는다. 모든 문자에 대해 간선과 진입 차수를 초기화한 뒤, 0인 노드부터 처리한다.

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

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# C is total length of all words, U is number of unique alien letters (<= 26).
# TC: O(C) - comparing adjacent words and processing topological sort graph
# SC: O(1) - unique letters and adjacency list bounded by 26 characters

from collections import deque


class Solution:

def alienOrder(self, words) -> str:
adj = {char: set() for word in words for char in word}
indegree = {char: 0 for word in words for char in word}

for i in range(len(words) - 1):
w1, w2 = words[i], words[i + 1]
min_len = min(len(w1), len(w2))

if len(w1) > len(w2) and w1[:min_len] == w2[:min_len]:
return ""

for j in range(min_len):
if w1[j] != w2[j]:
if w2[j] not in adj[w1[j]]:
adj[w1[j]].add(w2[j])
indegree[w2[j]] += 1
break

queue = deque([char for char in indegree if indegree[char] == 0])
result = []

while queue:
char = queue.popleft()
result.append(char)

for neighbor in adj[char]:
indegree[neighbor] -= 1
if indegree[neighbor] == 0:
queue.append(neighbor)

if len(result) < len(indegree):
return ""

return "".join(result)
15 changes: 15 additions & 0 deletions meeting-rooms/dolphinflow86.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.

🏷️ 알고리즘 패턴 분석

meeting-rooms/dolphinflow86.py
# N is the number of intervals.
# TC: O(N log N) - sorting the intervals by start time
# SC: O(1) - constant extra space


class Solution:

    def canAttendMeetings(self, intervals) -> bool:
        intervals.sort(key=lambda x: x[0])

        for i in range(1, len(intervals)):
            if intervals[i][0] < intervals[i - 1][1]:
                return False

        return True
  • 패턴: Greedy, Binary Search, Two Pointers
  • 설명: 회의실 배정 문제는 시작 시간 기준으로 정렬한 뒤 인접 간격을 비교하여 겹침을 확인한다. 간단히 하나의 조건을 체크하는 방식으로 최적의 탐색 없이도 해결되니 Greedy로 분류되며, 시작시간 정렬은 한 방향으로의 선형 검사에 해당한다.

📊 시간/공간 복잡도 분석

복잡도
Time O(N log N)
Space O(1)

피드백: 회의 간의 중복 여부를 선형 스캔으로 확인하기 위해 시작 시간을 먼저 오름차순으로 정렬한다.

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

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# N is the number of intervals.
# TC: O(N log N) - sorting the intervals by start time
# SC: O(1) - constant extra space


class Solution:

def canAttendMeetings(self, intervals) -> bool:
intervals.sort(key=lambda x: x[0])

for i in range(1, len(intervals)):
if intervals[i][0] < intervals[i - 1][1]:
return False

return True
20 changes: 20 additions & 0 deletions non-overlapping-intervals/dolphinflow86.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.

🏷️ 알고리즘 패턴 분석

non-overlapping-intervals/dolphinflow86.py
# N is the number of intervals.
# TC: O(N log N) - sorts intervals by end time and performs a single pass
# SC: O(N) - space required for sorting


class Solution:

    def eraseOverlapIntervals(self, intervals: list[list[int]]) -> int:
        intervals.sort(key=lambda x: x[1])

        remove_count = 0
        prev_end = float("-inf")

        for start, end in intervals:
            if start < prev_end:
                remove_count += 1
            else:
                prev_end = end

        return remove_count
  • 패턴: Greedy, Sort / Order Statistics
  • 설명: 간격을 끝나는 시점 기준으로 정렬한 뒤, 가능한 한 많이 남기려는 선택을 하며 충돌을 최소화하는 그리디 패턴의 전형적인 예이다. 끝점 기준 정렬과 단일 순회로 중복 제거를 수행한다.

📊 시간/공간 복잡도 분석

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

피드백: 종료점을 기준으로 정렬하고 한 번 순회하여 겹치는 구간의 수를 센다. 추가 공간은 상수로 충분하다.

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

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# N is the number of intervals.
# TC: O(N log N) - sorts intervals by end time and performs a single pass
# SC: O(N) - space required for sorting


class Solution:

def eraseOverlapIntervals(self, intervals: list[list[int]]) -> int:
intervals.sort(key=lambda x: x[1])

remove_count = 0
prev_end = float("-inf")

for start, end in intervals:
if start < prev_end:
remove_count += 1
else:
prev_end = end

return remove_count
28 changes: 28 additions & 0 deletions remove-nth-node-from-end-of-list/dolphinflow86.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.

🏷️ 알고리즘 패턴 분석

remove-nth-node-from-end-of-list/dolphinflow86.py
# N is the number of nodes in the linked list.
# TC: O(N) - single pass using two pointers with an (n + 1) gap
# SC: O(1) - modifies links in place using constant extra variables

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next


class Solution:

    def removeNthFromEnd(self, head, n: int):
        dummy = ListNode(0, head)
        fast = dummy
        slow = dummy

        for _ in range(n + 1):
            fast = fast.next

        while fast:
            fast = fast.next
            slow = slow.next

        slow.next = slow.next.next

        return dummy.next
  • 패턴: Two Pointers, Linked List
  • 설명: 두 포인터(두 스위치 포인터)로 널리 사용되는 패턴이며, 하나를 n+1 만큼 앞서 두고, 같이 움직여 제거할 노드를 찾는 방식이다. 연결리스트에서 끝에서 k번째를 제거하는典型 문제로 O(N) 단일 패스로 해결한다.

📊 시간/공간 복잡도 분석

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

피드백: 더블 포인터를 사용해 한 번의 순회로 제거 대상 위치를 찾는다. 추가 공간은 상수.

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

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# N is the number of nodes in the linked list.
# TC: O(N) - single pass using two pointers with an (n + 1) gap
# SC: O(1) - modifies links in place using constant extra variables

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next


class Solution:

def removeNthFromEnd(self, head, n: int):
dummy = ListNode(0, head)
fast = dummy
slow = dummy

for _ in range(n + 1):
fast = fast.next

while fast:
fast = fast.next
slow = slow.next

slow.next = slow.next.next

return dummy.next
21 changes: 21 additions & 0 deletions same-tree/dolphinflow86.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.

🏷️ 알고리즘 패턴 분석

same-tree/dolphinflow86.py
# N is the minimum number of nodes between trees p and q, and H is tree height.
# TC: O(N) - visits each node at most once comparing values
# SC: O(H) - recursion call stack proportional to tree height (O(N) in worst case)

# 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 isSameTree(self, p, q) -> bool:
        if not p and not q:
            return True
        if not p or not q or p.val != q.val:
            return False

        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
  • 패턴: Depth-First Search, Binary Search
  • 설명: 두 이진트리의 모든 노드를 재귀로 방문하며 동일한지 비교하는 DFS 패턴으로 구성됩니다. 트리의 좌우 자식에 대해 같은지 재귀적으로 확인합니다.

📊 시간/공간 복잡도 분석

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

피드백: 깊이우선 탐색으로 모든 노드를 방문하며 비교한다. 최악의 공간은 트리의 높이에 비례한다.

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

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# N is the minimum number of nodes between trees p and q, and H is tree height.
# TC: O(N) - visits each node at most once comparing values
# SC: O(H) - recursion call stack proportional to tree height (O(N) in worst case)

# 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 isSameTree(self, p, q) -> bool:
if not p and not q:
return True
if not p or not q or p.val != q.val:
return False

return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
Loading