Skip to content

[yyyyyyyyyKim] WEEK 12 solutions #1591

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 21, 2025
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
26 changes: 26 additions & 0 deletions non-overlapping-intervals/yyyyyyyyyKim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
class Solution:
def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:

# 그리디
# 시간복잡도 O(n log n), 공간복잡도 O(1)

# 시작점 기준 정렬
intervals.sort()
answer = 0 # 제거할 개수
curr_end = intervals[0][1] # 첫 구간 끝나는 지점 초기화

for i in range(1,len(intervals)):
start, end = intervals[i]

# 겹치는 경우(제거)
if start < curr_end:
# 현재 구간 제거
answer += 1
# 더 작은 지점 남기기(겹치는 부분을 줄이기위해)
curr_end = min(curr_end, end)

# 안겹치는 경우(현재 구간을 다음 기준으로 탐색)
else:
curr_end = end

return answer
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from typing import (
List,
)

class Solution:
"""
@param n: the number of vertices
@param edges: the edges of undirected graph
@return: the number of connected components
"""
def count_components(self, n: int, edges: List[List[int]]) -> int:

# DFS
# 시간 복잡도 O(n + e), 공간복잡도 O(n + e) // n=노드수, e=간선수
# 인접 리스트 방식으로 무방향 그래프 생성
graph = [[] for _ in range(n)]
for i, j in edges:
graph[i].append(j)
graph[j].append(i)

visited = set() # 방문한 노드 저장할 집합
answer = 0 # 연결 요소 개수

# 현재 node와 연결된 모든 노드 방문 처리하는 함수
def dfs(node):
# 이미 방문한 노드라면 dfs 종료
if node in visited:
return
visited.add(node) # node 방문처리
# 연결된 노드들도 탐색
for i in graph[node]:
dfs(i)

# 모든 노드 탐색 후 연결 요소 개수 세기
for i in range(n):
# 방문하지 않은 노드라면 dfs 탐색하고 연결요소(answer) +1
if i not in visited:
dfs(i)
answer += 1

return answer
29 changes: 29 additions & 0 deletions remove-nth-node-from-end-of-list/yyyyyyyyyKim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# 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]:

# 투포인터
# 시간복잡도 O(n), 공간복잡도 O(1)

# 더미 노드 사용(head삭제되는경우대비)
dummy = ListNode(0, head)
slow, fast = dummy, dummy

# fast를 n칸 이동(slow와의 간격n으로 유지)
for _ in range(n):
fast = fast.next

# fast가 끝에 도달할때까지 slow와 한 칸씩 이동
while fast.next:
fast = fast.next
slow = slow.next

# slow.next = 삭제대상, 건너뛰고연결(삭제처리)
slow.next = slow.next.next

# 새로운 head 반환
return dummy.next
25 changes: 25 additions & 0 deletions same-tree/yyyyyyyyyKim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# 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:

# DFS
# 시간복잡도 O(n), 공간복잡도 O(n)
def dfs(node1, node2):
# 둘 다 없으면 같은 트리
if not node1 and not node2:
return True
# 둘 중 하나만 없으면 다른 트리
if not node1 or not node2:
return False
# 둘의 값이 다르면 다른 트리
if node1.val != node2.val:
return False
# 좌우서브트리 비교
return dfs(node1.left, node2.left) and dfs(node1.right, node2.right)

return dfs(p, q)
58 changes: 58 additions & 0 deletions serialize-and-deserialize-binary-tree/yyyyyyyyyKim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Codec:
# DFS

# 이진트리 -> 문자열 변환(직렬화)
# 시간복잡도 O(n), 공간복잡도 O(n)
def serialize(self, root):
"""Encodes a tree to a single string.

:type root: TreeNode
:rtype: str
"""
if not root:
return 'null'

# 재귀 호출로 노드값을 문자열로 저장
return str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)


# 문자열 -> 이진트리 변환(역직렬화)
# 시간복잡도 O(n), 공간복잡도 O(n)
def deserialize(self, data):
"""Decodes your encoded data to tree.

:type data: str
:rtype: TreeNode
"""
# ','를 기준으로 끊어서 리스트로 변환
s = data.split(',')

def dfs():
# 맨 앞부터 꺼내기
val = s.pop(0)

# null이면 자식 노드 없음
if val == 'null':
return None

node = TreeNode(int(val)) # 현재 노드
node.left = dfs() # 왼쪽 서브트리
node.right = dfs() # 오른쪽 서브트리

return node

return dfs()



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