[yuseok89] WEEK 12 Solutions - #2855
Open
yuseok89 wants to merge 4 commits into
Open
Conversation
Contributor
There was a problem hiding this comment.
🏷️ 알고리즘 패턴 분석
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 와의 비교로 중복을 제거한다. 정렬이 주된 시간 복잡도이다.
개선 제안: 현재 구현이 적절해 보입니다.
Contributor
There was a problem hiding this comment.
🏷️ 알고리즘 패턴 분석
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 만큼 먼저 이동시키고 뒤따르는 포인터를 함께 이동시켜 제거할 노드를 찾는다.
개선 제안: 현재 구현이 적절해 보입니다.
Contributor
📊 yuseok89 님의 학습 현황이번 주 제출 문제
누적 학습 요약
문제 풀이 현황
🤖 이 댓글은 GitHub App을 통해 자동으로 작성되었습니다. 🔢 API 사용량 (gpt-5-nano)
|
Contributor
There was a problem hiding this comment.
🏷️ 알고리즘 패턴 분석
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) | ✅ |
피드백: 피크리컬 재귀로 모든 노드를 비교하며, 자식 비교를 동시 진행한다.
개선 제안: 현재 구현이 적절해 보입니다.
Contributor
There was a problem hiding this comment.
🏷️ 알고리즘 패턴 분석
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 기반 직렬화 방식으로 모든 노드 정보를 보존한다.
개선 제안: 현재 구현이 적절해 보입니다.
💡 풀이에 시간/공간 복잡도를 주석으로 남겨보세요!
alphaorderly
reviewed
Sep 9, 2026
Contributor
There was a problem hiding this comment.
너무 깔끔하고 좋은 코드이신데요!
얼리 리턴을 사용하시면 코드의 depth를 줄일수 있지 않을까 하는 아주 미세한 아쉬움이 있습니다!
물론 개인의 취향이긴 합니다!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
답안 제출 문제
작성자 체크 리스트
In Review로 설정해주세요.검토자 체크 리스트
Important
본인 답안 제출 뿐만 아니라 다른 분 PR 하나 이상을 반드시 검토를 해주셔야 합니다!