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
12 changes: 12 additions & 0 deletions non-overlapping-intervals/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.

🏷️ 알고리즘 패턴 분석

non-overlapping-intervals/yuseok89.py
# TC: O(NlogN)
# SC: O(1)
class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        end, cnt = float('-inf'), 0
        for s, e in sorted(intervals, key=lambda x: x[1]):
            if s >= end:
                end = e
            else:
                cnt += 1
        return cnt
  • 패턴: Greedy
  • 설명: 종료 시점을 오름차순으로 정렬한 뒤, 현재 선택된 간격의 끝과 비교하여 겹치는지 판단하는 단순 탐욕적 선택(Greedy) 패턴이다. 남은 간격의 수를 최소화하기 위해 가장 빨리 끝나는 간격을 선택한다.

📊 시간/공간 복잡도 분석

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

피드백: 끝 지점을 기준으로 방문하며 현재 선택된 마지막 끝점 end 와의 비교로 중복을 제거한다. 정렬이 주된 시간 복잡도이다.

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# TC: O(NlogN)
# SC: O(1)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

sorted()는 새 리스트를 만들지 않나요? 그럼 공간 복잡도가 O(N)이 될 수도 있겠네요.

class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
end, cnt = float('-inf'), 0
for s, e in sorted(intervals, key=lambda x: x[1]):
if s >= end:
end = e
else:
cnt += 1
return cnt

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

🏷️ 알고리즘 패턴 분석

remove-nth-node-from-end-of-list/yuseok89.py
# TC: O(N)
# SC: O(1)
# 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]:

        fwd, flw = head, head

        for _ in range(n):
            fwd = fwd.next

        if not fwd:
            return head.next

        while fwd.next:
            fwd = fwd.next
            flw = flw.next

        flw.next = flw.next.next

        return head
  • 패턴: Two Pointers, Linked List
  • 설명: 배열이 아닌 연결리스트에서 끝에서 n번째 노드를 제거하기 위해 두 포인터를 활용합니다. 한 포인터를 n만큼 먼저 전진시키고, 함께 끝까지 이동시키며 대상 노드를 바로 앞에서 제거하는 방식입니다.

📊 시간/공간 복잡도 분석

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

피드백: 전방 포인터를 n 만큼 먼저 이동시키고 뒤따르는 포인터를 함께 이동시켜 제거할 노드를 찾는다.

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# TC: O(N)
# SC: O(1)
# 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]:

fwd, flw = head, head

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

fwdforward로 바로 읽히는데, flwfollow의 줄임이겠죠?


for _ in range(n):
fwd = fwd.next

if not fwd:
return head.next

while fwd.next:
fwd = fwd.next
flw = flw.next

flw.next = flw.next.next

return head

20 changes: 20 additions & 0 deletions same-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.

🏷️ 알고리즘 패턴 분석

same-tree/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 isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:

        if p and q:
            if p.val != q.val:
                return False
            return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
        elif not p and not q:
            return True
        else:
            return False
  • 패턴: DFS, Divide and Conquer
  • 설명: 두 트리의 대응 노드를 재귀적으로 비교하며 자식 노드로 내려가며 같은지 확인하는 분할 정복 형태의 DFS 패턴이 적용됩니다. 각 재귀에서 노드 값 비교와 좌우 서브트리 비교를 함께 수행합니다.

📊 시간/공간 복잡도 분석

유저 분석 실제 분석 결과
Time O(N) O(n)
Space O(H) 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.

너무 깔끔하고 좋은 코드이신데요!
얼리 리턴을 사용하시면 코드의 depth를 줄일수 있지 않을까 하는 아주 미세한 아쉬움이 있습니다!
물론 개인의 취향이긴 합니다!

Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# 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 isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:

if p and q:
if p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
elif not p and not q:
return True
else:
return False

74 changes: 74 additions & 0 deletions serialize-and-deserialize-binary-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.

🏷️ 알고리즘 패턴 분석

serialize-and-deserialize-binary-tree/yuseok89.py
# TC: O(N)
# SC: O(N)
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.

        :type root: TreeNode
        :rtype: str
        """

        arr = []
        q = deque()
        q.append(root)

        while q:

            cur = q.popleft()

            if cur:
                arr.append(str(cur.val))
                q.append(cur.left)
                q.append(cur.right)
            else:
                arr.append('n')

        return ','.join(arr)


    def deserialize(self, data):
        """Decodes your encoded data to tree.

        :type data: str
        :rtype: TreeNode
        """

        values = data.split(',')
        n = len(values)

        if values[0] == 'n':
            return None

        root = TreeNode(int(values[0]))
        q = deque()
        q.append(root)
        idx = 1

        while idx < n:
            par = q.popleft()

            if values[idx] != 'n':
                par.left = TreeNode(int(values[idx]))
                q.append(par.left)
            idx += 1

            if idx < n and values[idx] != 'n':
                par.right = TreeNode(int(values[idx]))
                q.append(par.right)
            idx += 1

        return root

# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# ans = deser.deserialize(ser.serialize(root))
  • 패턴: Breadth-First Search, Binary Search
  • 설명: serialization/deserialization 은 넓이우선 탐색(BFS)로 트리를 레벨 순서로 순회하여 큐를 이용해 노드를 처리합니다. 따라서 BFS 패턴에 해당하며, 트리 구조를 탐색하고 재구성하는 과정이 핵심입니다.

📊 시간/공간 복잡도 분석

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

피드백: 전형적인 BFS 기반 직렬화 방식으로 모든 노드 정보를 보존한다.

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

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

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

class Codec:

def serialize(self, root):
"""Encodes a tree to a single string.

:type root: TreeNode
:rtype: str
"""

arr = []
q = deque()
q.append(root)

while q:

cur = q.popleft()

if cur:
arr.append(str(cur.val))
q.append(cur.left)
q.append(cur.right)
else:
arr.append('n')

return ','.join(arr)


def deserialize(self, data):
"""Decodes your encoded data to tree.

:type data: str
:rtype: TreeNode
"""

values = data.split(',')
n = len(values)

if values[0] == 'n':
return None

root = TreeNode(int(values[0]))
q = deque()
q.append(root)
idx = 1

while idx < n:
par = q.popleft()

if values[idx] != 'n':
par.left = TreeNode(int(values[idx]))
q.append(par.left)
idx += 1

if idx < n and values[idx] != 'n':
par.right = TreeNode(int(values[idx]))
q.append(par.right)
idx += 1

return root

# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# ans = deser.deserialize(ser.serialize(root))

Loading