Skip to content
Open
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

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.

🏷️ 알고리즘 패턴 분석

number-of-connected-components-in-an-undirected-graph/parkhojeong.py
class Solution:
    def countComponents(self, n: int, edges: List[List[int]]) -> int:
        edge_dic = {i: [i] for i in range(n)}

        for edge in edges:
            start, end = sorted(edge)
            edge_dic[start].append(end)
            edge_dic[end].append(start)

        def traverse(idx: int):
            while edge_dic[idx]:
                end = edge_dic[idx].pop()
                traverse(end)

        cnt = 0
        for i in range(n):
            if len(edge_dic[i]) > 0:
                cnt += 1
                traverse(i)

        return cnt
  • 패턴: Depth-First Search, Hash Map / Hash Set
  • 설명: 그래프를 DFS로 탐색하며 연결 성분의 개수를 센다. 각 정점의 인접 리스트를 해시 맵으로 관리하고, 방문 여부를 리스트 길이로 판단한다.

📊 시간/공간 복잡도 분석

복잡도
Time O(n + m)
Space O(n + m)

피드백: 인접 리스트를 한 방향으로만 탐색하는 재귀가 없이 스택으로 구현되어 있고, 각 정점을 한 번씩 방문하므로 시간은 간선 수와 정점 수의 합에 비례한다.

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

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
edge_dic = {i: [i] for i in range(n)}

for edge in edges:
start, end = sorted(edge)
edge_dic[start].append(end)
edge_dic[end].append(start)

def traverse(idx: int):
while edge_dic[idx]:
end = edge_dic[idx].pop()
traverse(end)

cnt = 0
for i in range(n):
if len(edge_dic[i]) > 0:
cnt += 1
traverse(i)

return cnt

28 changes: 28 additions & 0 deletions remove-nth-node-from-end-of-list/parkhojeong.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/parkhojeong.py
# 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: Optional[ListNode], n: int) -> Optional[ListNode]:
        cnt = 0
        cur = head
        while cur:
            cnt += 1
            cur = cur.next

        dummy = ListNode()
        dummy.next = head
        prev = dummy
        cur = head
        i = 0
        while cur:
            if cnt - n == i:
                prev.next = cur.next
                break

            prev = cur
            cur = cur.next
            i += 1

        return dummy.next
  • 패턴: Two Pointers, Linked List
  • 설명: 두 포인터를 이용해 끝에서 n번째 노드를 제거하는 과정을 구현하므로 Two Pointers 패턴이 가장 적합합니다. 또한 Linked List 구조를 다루는 일반적인 패턴으로 linked list 관련 흐름도 같이 보입니다.

📊 시간/공간 복잡도 분석

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

피드백: 카운트를 이용해 두 번째 포인터를 조정하는 방식으로 추가 포인터를 사용하지 않고도 제거 가능하다.

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

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

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.

이거 Single pass로 해결하는게 진짜 괜찮던데 한번 시도 해 보시는것도 좋겠네요

Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# 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: Optional[ListNode], n: int) -> Optional[ListNode]:
cnt = 0
cur = head
while cur:
cnt += 1
cur = cur.next

dummy = ListNode()
dummy.next = head
prev = dummy
cur = head
i = 0
while cur:
if cnt - n == i:
prev.next = cur.next
break

prev = cur
cur = cur.next
i += 1

return dummy.next
22 changes: 22 additions & 0 deletions same-tree/parkhojeong.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/parkhojeong.py
# 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: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if p is None and q is None:
            return True

        if (p is None and q is not None) or (p is not None and q is None):
            return False

        if (p.left or q.left) and not self.isSameTree(p.left, q.left):
            return False

        if (p.right or q.right) and not self.isSameTree(p.right, q.right):
            return False

        return p.val == q.val
  • 패턴: Depth-First Search, Binary Search, Hash Map / Hash Set
  • 설명: 트리 구조를 재귀적으로 순회하며 두 트리의 노드 값을 비교하고 좌우 자식까지 동일 여부를 확인하는 방식으로 동작합니다. 재귀를 통해 DFS 형태로 같은지 여부를 깊이 우선으로 검사합니다.

📊 시간/공간 복잡도 분석

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

피드백: 각 재귀 호출이 트리의 같은 위치의 노드를 비교하며, 최악의 경우 트리 높이에 비례하는 공간이 필요하다.

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

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

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.

초반에 엄청나게 많은 조건들 정리하는게 가독성 상 좋지 않을까요?

Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# 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: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if p is None and q is None:
return True

if (p is None and q is not None) or (p is not None and q is None):
return False

if (p.left or q.left) and not self.isSameTree(p.left, q.left):
return False

if (p.right or q.right) and not self.isSameTree(p.right, q.right):
return False

return p.val == q.val

Loading