Skip to content

Commit 1ae487f

Browse files
authored
Merge pull request #2286 from doh6077/main
[doh6077] WEEK 11 solutions
2 parents 991f641 + 9ea4c6c commit 1ae487f

5 files changed

Lines changed: 174 additions & 0 deletions

File tree

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
from collections import deque
8+
class Solution:
9+
def maxPathSum(self, root: Optional[TreeNode]) -> int:
10+
11+
# # Initially thought I need to use BFS ( misunderstood the question)
12+
# if not root:
13+
# return
14+
# queue = deque([root])
15+
# result = []
16+
# val = 0
17+
# max_sum = float('-inf')
18+
# while queue:
19+
# currentNode = queue.popleft()
20+
# result.append(currentNode.val)
21+
# val += currentNode.val
22+
23+
# if currentNode.left:
24+
# queue.append(currentNode.left)
25+
# val += currentNode.left.val
26+
# if currentNode.right:
27+
# queue.append(currentNode.right)
28+
# val += currentNode.right.val
29+
# max_sum = max(val, max_sum)
30+
# val = 0
31+
# return max_sum
32+
res = [root.val]
33+
34+
def dfs(root):
35+
if not root:
36+
return 0
37+
leftMax = dfs(root.left)
38+
rightMax = dfs(root.right)
39+
# 자식 값이 음수일경우 0으로 처리
40+
leftMax = max(leftMax, 0)
41+
rightMax = max(rightMax, 0)
42+
# "지금까지 발견한 경로 중 최고의 합"을 res[0]에 저장
43+
# Job 1: 나를 꺾임점(Anchor)으로 하는 '아치형' 경로 계산
44+
res[0] = max(res[0], root.val + leftMax + rightMax)
45+
# Job 2: 부모에게 올릴 '직선' 경로 리턴
46+
return root.val + max(leftMax, rightMax)
47+
dfs(root)
48+
return res[0]

graph-valid-tree/doh6077.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution:
2+
def validTree(self, n: int, edges: List[List[int]]) -> bool:
3+
# Valid Tree
4+
# 1. no loop
5+
# 2. no disconnected node
6+
# Use DFS and Hashset to track visited nodes
7+
if not n:
8+
return True
9+
10+
adj = {i:[] for i in range(n)}
11+
for n1, n2 in edges:
12+
adj[n1].append(n2)
13+
adj[n2].append(n1)
14+
visit = set()
15+
def dfs(i, prev):
16+
# Base case
17+
if i in visit:
18+
return False
19+
visit.add(i)
20+
# check neighbor nodes
21+
for j in adj[i]:
22+
if j == prev:
23+
continue
24+
if not dfs(j,i):
25+
return False
26+
return True
27+
28+
return dfs(0, -1) and n == len(visit)

merge-intervals/doh6077.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# 56. Merge Intervals
2+
3+
# First Try:
4+
# Time Complexity:O(N)
5+
# Brute Force with Two Pointers
6+
# 포인터를 사용해서 merge 해야하는 구간을 확인한다
7+
# 효율적이지 않아서 더 나은 방법이 있을 거 같다. 해당 문제를 봤을때 일단 기본적으로 정렬을 하고 pointer를 사용하는 방법을 떠올렸다.
8+
# merge 해야하는 구간은 2가지가 있다. 1. left의 end가 right의 start보다 크거나 같은 경우 2. left가 right의 구간을 전체를 다 포함하는경우 , 이경우 right를 지운다.
9+
class Solution:
10+
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
11+
# Use two pointers
12+
intervals = sorted(intervals)
13+
left, right = 0, 1
14+
n = len(intervals)
15+
while left < right and right < n:
16+
if intervals[left][1] >= intervals[right][0] and intervals[left][1] >= intervals[right][1]:
17+
del intervals[right]
18+
n = len(intervals)
19+
# and intervals[left][1] < intervals[right][1]
20+
elif intervals[left][1] >= intervals[right][0]:
21+
intervals[left] = [intervals[left][0], intervals[right][1]]
22+
del intervals[right]
23+
n = len(intervals)
24+
# merge 할 경우가 아니면 다음 인덱스로 넘어가서 새로 비교한다
25+
else:
26+
left += 1
27+
right += 1
28+
return intervals
29+
30+
# Optimized Solution
31+
intervals.sort(key=lambda interval: interval[0])
32+
merged = []
33+
34+
for interval in intervals:
35+
if not merged or merged[-1][1] < interval[0]:
36+
merged.append(interval)
37+
else:
38+
merged[-1] = [merged[-1][0], max(merged[-1][1], interval[1])]
39+
40+
return merged

missing-number/doh6077.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Missing Number
2+
class Solution:
3+
def missingNumber(self, nums: List[int]) -> int:
4+
# First Solution: Time Complexity: O(n^2)
5+
n = len(nums)
6+
7+
for i in range(0,n + 1):
8+
if i not in nums:
9+
return i
10+
11+
# Time Complexity: O(n)
12+
n = len(nums)
13+
# calculate the sum of first n numbers
14+
sum_val = n * (n + 1) // 2
15+
return sum_val - sum(nums)
16+

reorder-list/doh6077.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
class Solution:
7+
def reorderList(self, head: Optional[ListNode]) -> None:
8+
"""
9+
Do not return anything, modify head in-place instead.
10+
"""
11+
# Time Complexity: O(N)
12+
# The order:
13+
# 0, n, 1, n -1, 2, n-3 ...
14+
# first Idea
15+
# need to save the index of the original head
16+
# Hashmap: iterate through the head until head it none, save index as key and head.val as value
17+
head_hash = {}
18+
temp = head
19+
index = 0
20+
length = 0
21+
# Save index and value in the hashmap
22+
while temp is not None:
23+
head_hash[index] = temp.val
24+
temp = temp.next
25+
index += 1
26+
length += 1
27+
# reset index to 0, and use it to iterate through the head again
28+
index = 0
29+
# to keep track of n-1, n-2, n-3 ...
30+
count = 1
31+
# Iterate through the head again and change the value based on the index
32+
while head is not None:
33+
res = index % 2
34+
# if the index is even number
35+
if res == 0:
36+
head.val = head_hash[index/2]
37+
# n, n-1, n-2 when the index is odd
38+
else:
39+
head.val = head_hash[length - count]
40+
count += 1
41+
index += 1
42+
head = head.next

0 commit comments

Comments
 (0)