Skip to content

[yuseok89] WEEK 12 Solutions - #2855

Open
yuseok89 wants to merge 4 commits into
DaleStudy:mainfrom
yuseok89:main
Open

[yuseok89] WEEK 12 Solutions#2855
yuseok89 wants to merge 4 commits into
DaleStudy:mainfrom
yuseok89:main

Conversation

@yuseok89

@yuseok89 yuseok89 commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

답안 제출 문제

작성자 체크 리스트

  • Projects의 오른쪽 버튼(▼)을 눌러 확장한 뒤, Week를 현재 주차로 설정해주세요.
  • 문제를 모두 푸시면 프로젝트에서 StatusIn Review로 설정해주세요.
  • 코드 검토자 1분 이상으로부터 승인을 받으셨다면 PR을 병합해주세요.

검토자 체크 리스트

Important

본인 답안 제출 뿐만 아니라 다른 분 PR 하나 이상을 반드시 검토를 해주셔야 합니다!

  • 바로 이전에 올라온 PR에 본인을 코드 리뷰어로 추가해주세요.
  • 본인이 검토해야하는 PR의 답안 코드에 피드백을 주세요.
  • 토요일 전까지 PR을 병합할 수 있도록 승인해주세요.

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 와의 비교로 중복을 제거한다. 정렬이 주된 시간 복잡도이다.

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

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 만큼 먼저 이동시키고 뒤따르는 포인터를 함께 이동시켜 제거할 노드를 찾는다.

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

@dalestudy

dalestudy Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

📊 yuseok89 님의 학습 현황

이번 주 제출 문제

문제 난이도 유형 분석
non-overlapping-intervals Medium ✅ 의도한 유형
remove-nth-node-from-end-of-list Medium ✅ 의도한 유형
same-tree Easy ✅ 의도한 유형
serialize-and-deserialize-binary-tree Hard ✅ 의도한 유형

누적 학습 요약

  • 풀이한 문제: 53 / 75개
  • 이번 주 유형 일치율: 100% (4문제 중 4문제 일치)

문제 풀이 현황

카테고리 진행도 완료
Array ■■■■■■■ 10 / 10 (Medium 7, Easy 3)
Dynamic Programming ■■■■■■□ 10 / 11 (Easy 1, Medium 9)
Linked List ■■■■■■□ 5 / 6 (Easy 3, Hard 1, Medium 1)
Binary ■■■■■■□ 4 / 5 (Easy 3, Medium 1)
String ■■■■■■□ 8 / 10 (Medium 4, Hard 1, Easy 3)
Matrix ■■■■■□□ 3 / 4 (Medium 3)
Heap ■■■■■□□ 2 / 3 (Hard 1, Medium 1)
Graph ■■■■□□□ 5 / 8 (Medium 5)
Tree ■■■□□□□ 6 / 14 (Hard 1, Medium 3, Easy 2)
Interval ■□□□□□□ 1 / 5 (Medium 1)

🤖 이 댓글은 GitHub App을 통해 자동으로 작성되었습니다.

🔢 API 사용량 (gpt-5-nano)
요청 입력 토큰 출력 토큰 합계 비용
1 1,618 162 1,780 $0.000146

@yuseok89 yuseok89 moved this to In Review in 리트코드 스터디 8기 Sep 8, 2026
Comment thread 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.

🏷️ 알고리즘 패턴 분석

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 기반 직렬화 방식으로 모든 노드 정보를 보존한다.

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

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

Comment thread 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.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: In Review

Development

Successfully merging this pull request may close these issues.

2 participants