Skip to content

[yyyyyyyyyKim] WEEK 11 solutions #1568

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 14, 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
30 changes: 30 additions & 0 deletions binary-tree-maximum-path-sum/yyyyyyyyyKim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# 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 maxPathSum(self, root: Optional[TreeNode]) -> int:

# DFS + 분할정복형 DP
# 시간복잡도 O(n), 공간복잡도 O(n)
self.answer = float('-inf') # 최저값을 초기값으로 세팅(dfs함수에서도 쓰일 수 있게 인스턴스변수 선언해서 전역변수처럼 사용)

def dfs(node):
if not node:
return 0

# 왼쪽, 오른쪽 서브트리에서 최대합(음수라면 버리고 0 가져가기)
left = max(0,dfs(node.left))
right = max(0,dfs(node.right))

# 현재 노드를 포함하는 최대합으로 answer 업데이트
self.answer = max(self.answer, left + right + node.val)

# 왼쪽,오른쪽 중 최대값 선택(한방향이니까)해서 부모에게 리턴
return max(left, right) + node.val


dfs(root)
return self.answer
46 changes: 46 additions & 0 deletions graph-valid-tree/yyyyyyyyyKim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from typing import (
List,
)

class Solution:
"""
@param n: An integer
@param edges: a list of undirected edges
@return: true if it's a valid tree, or false
"""
def valid_tree(self, n: int, edges: List[List[int]]) -> bool:
# DFS(그래프 탐색)
# 시간복잡도 O(n), 공간복잡도 O(n)

# 트리의 간선 수는 항상 "노드 수 -1"(아니면 바로 False)
if len(edges) != n-1:
return False

# 인접 리스트 방식으로 그래프 생성
graph = [[] for _ in range(n)]
for i, j in edges:
graph[i].append(j)
graph[j].append(i)

# set사용(방문여부만 빠르게 탐색(in연산 시간복잡도 O(1))
visited = set()

def dfs(node,prev):
# 이미 방문한 노드면 종료
if node in visited:
return
visited.add(node)

# 현재 노드와 이웃 탐색
for i in graph[node]:
# 바로 이전 노드 패스(무방향 그래프니까)
if i == prev:
continue
dfs(i, node)


# 0번 노드부터 탐색 시작
dfs(0, -1)

# 방문한 노드 수와 전체 노드 수가 같으면 연결 그래프 -> 트리
return len(visited) == n
18 changes: 18 additions & 0 deletions merge-intervals/yyyyyyyyyKim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
# 시간복잡도 O(n log n), 공간복잡도 O(n)

intervals.sort() # 정렬
answer = []

for i in intervals:

# answer가 비어있거나 answer의 맨 뒤 값이 i의 첫 번째 값보다 작을 경우(겹치지않는경우) answer에 i추가
if not answer or answer[-1][1] < i[0]:
answer.append(i)

# 값이 겹치는 경우 합치기(더 큰 값으로 업데이트)
else:
answer[-1][1] = max(answer[-1][1],i[1])

return answer
8 changes: 8 additions & 0 deletions missing-number/yyyyyyyyyKim.py
Copy link
Contributor

Choose a reason for hiding this comment

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

저는 boolean 배열로 방문 여부를 체크해서 풀었는데, 총 합이 동일한지 여부로 풀면 이렇게 간단한 한 줄 풀이도 가능하네요. 제 reviewer깨서도 동일한 방법을 조언해주셨는데, 이렇게 간략한 풀이를 보니 좀 더 직관적으로 와닿았습니다. ㅎㅎ

Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class Solution:
def missingNumber(self, nums: List[int]) -> int:

# 시간복잡도 O(n), 공간복잡도 O(1)
# n = nums의 길이
# 0부터 n까지 총합 = (n*(n+1))//2
# 총합에서 nums의 합을 빼면 빠진 수를 구할 수 있음
return (len(nums)*(len(nums)+1))//2 - sum(nums)
42 changes: 42 additions & 0 deletions reorder-list/yyyyyyyyyKim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
"""
Do not return anything, modify head in-place instead.
"""
# 시간복잡도 o(n), 공간복잡도 O(1)

# 리스트 중간 지점 찾기
slow, fast = head, head

while fast and fast.next:
slow = slow.next
fast = fast.next.next

# 중간에서 뒷부분 뒤집기
curr = slow.next
prev = None
slow.next = None

while curr:
next_temp = curr.next
curr.next = prev
prev = curr
curr = next_temp

# 앞부분과 뒷부분 합치기
first, second = head, prev

while second:
temp1 = first.next
temp2 = second.next

first.next = second
second.next = temp1

first = temp1
second = temp2