Skip to content

Commit 4d40f78

Browse files
authored
Merge pull request #1576 from ayosecu/main
[ayosecu] Week 11 Solutions
2 parents 40f3844 + b00d511 commit 4d40f78

File tree

5 files changed

+212
-0
lines changed

5 files changed

+212
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
from typing import Optional
2+
3+
class TreeNode:
4+
def __init__(self, val=0, left=None, right=None):
5+
self.val = val
6+
self.left = left
7+
self.right = right
8+
class Solution:
9+
"""
10+
- Time Complexity: O(n), n = The number of nodes
11+
- Space Complexity: O(H), H = The height of Tree
12+
"""
13+
def maxPathSum(self, root: Optional[TreeNode]) -> int:
14+
self.max_sum = float("-inf")
15+
16+
def dfs(node):
17+
if not node:
18+
return 0
19+
20+
# Find max sum from the left and right children (more than 0)
21+
l_sum = max(dfs(node.left), 0)
22+
r_sum = max(dfs(node.right), 0)
23+
24+
# Calculate current sum and update max_sum
25+
current_sum = node.val + l_sum + r_sum
26+
self.max_sum = max(self.max_sum, current_sum)
27+
28+
# Return larger path
29+
return node.val + max(l_sum, r_sum)
30+
31+
dfs(root)
32+
33+
return self.max_sum
34+
35+
def do_test():
36+
sol = Solution()
37+
38+
root1 = TreeNode(1)
39+
root1.left = TreeNode(2)
40+
root1.right = TreeNode(3)
41+
e1 = 6
42+
r1 = sol.maxPathSum(root1)
43+
print(f"TC 1 is Passed!" if r1 == e1 else f"TC 1 is Failed! - Expected: {e1}, Result: {r1}")
44+
45+
root2 = TreeNode(-10)
46+
root2.left = TreeNode(9)
47+
root2.right = TreeNode(20)
48+
root2.right.left = TreeNode(15)
49+
root2.right.right = TreeNode(7)
50+
e2 = 42
51+
r2 = sol.maxPathSum(root2)
52+
print(f"TC 2 is Passed!" if r2 == e2 else f"TC 2 is Failed! - Expected: {e2}, Result: {r2}")
53+
54+
do_test()

graph-valid-tree/ayosecu.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from collections import deque, defaultdict
2+
3+
class Solution:
4+
"""
5+
- Time Complexity: O(n + e), e = len(edges)
6+
- Space Complexity: O(n), The size of dictionary
7+
"""
8+
def validTree(self, n, edges):
9+
# The number of edges must be "n - 1"
10+
if len(edges) != n - 1:
11+
return False
12+
13+
dic = defaultdict(list)
14+
for u, v in edges:
15+
dic[u].append(v)
16+
dic[v].append(u)
17+
18+
# BFS for visiting all nodes
19+
visited = set()
20+
dq = deque([0])
21+
22+
while dq:
23+
node = dq.popleft()
24+
if node in visited:
25+
continue
26+
visited.add(node)
27+
for next in dic[node]:
28+
if next not in visited:
29+
dq.append(next)
30+
31+
# Check all nodes were visited
32+
return len(visited) == n
33+
34+
tc = [
35+
(5, [[0, 1], [0, 2], [0, 3], [1, 4]], True),
36+
(5, [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], False)
37+
]
38+
39+
sol = Solution()
40+
for i, (n, edges, e) in enumerate(tc, 1):
41+
r = sol.validTree(n, edges)
42+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

merge-intervals/ayosecu.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
- Time complexity: O(nlogn), n = len(intervals)
6+
- Space Complexity: O(1), If output variable excluded.
7+
"""
8+
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
9+
result = []
10+
intervals.sort(key=lambda x: x[0])
11+
12+
for interval in intervals:
13+
if not result or result[-1][1] < interval[0]:
14+
result.append(interval)
15+
else:
16+
result[-1][1] = max(result[-1][1], interval[1])
17+
18+
return result
19+
20+
21+
tc = [
22+
([[1, 3], [2, 6], [8, 10], [15, 18]], [[1, 6], [8, 10], [15, 18]]),
23+
([[1, 4], [4, 5]], [[1, 5]])
24+
]
25+
26+
solution = Solution()
27+
for i, (intervals, e) in enumerate(tc, 1):
28+
r = solution.merge(intervals)
29+
print(f"TC {i} is Passed!" if r == e else f"TC 1 is Failed! - Expected: {e}, Result: {r}")

missing-number/ayosecu.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
- Time Complexity: O(n), n = len(nums)
6+
- Space Complexity: O(1)
7+
"""
8+
def missingNumber(self, nums: List[int]) -> int:
9+
n = len(nums)
10+
total = (1 + n) * n // 2
11+
12+
for num in nums:
13+
total -= num
14+
15+
return total
16+
17+
tc = [
18+
([3, 0, 1], 2),
19+
([0, 1], 2),
20+
([9, 6, 4, 2, 3, 5, 7, 0, 1], 8)
21+
]
22+
23+
sol = Solution()
24+
for i, (n, e) in enumerate(tc, 1):
25+
r = sol.missingNumber(n)
26+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

reorder-list/ayosecu.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
from typing import Optional
2+
from collections import deque
3+
4+
class ListNode:
5+
def __init__(self, val=0, next=None):
6+
self.val = val
7+
self.next = next
8+
9+
class Solution:
10+
"""
11+
- Time Complexity: O(N), N = The number of nodes.
12+
- Space Complexity: O(N)
13+
"""
14+
def reorderList(self, head: Optional[ListNode]) -> None:
15+
dq = deque()
16+
17+
cur = head
18+
while cur:
19+
dq.append(cur)
20+
cur = cur.next
21+
22+
dummy = ListNode(-1)
23+
cur = dummy
24+
flag = True
25+
while dq:
26+
if flag:
27+
cur.next = dq.popleft()
28+
else:
29+
cur.next = dq.pop()
30+
cur = cur.next
31+
flag = not flag
32+
cur.next = None
33+
34+
return dummy.next
35+
36+
### TC Helpers ###
37+
def build_linked_list(values):
38+
dummy = ListNode(0)
39+
current = dummy
40+
for v in values:
41+
current.next = ListNode(v)
42+
current = current.next
43+
return dummy.next
44+
45+
def linked_list_to_list(head):
46+
result = []
47+
while head:
48+
result.append(head.val)
49+
head = head.next
50+
return result
51+
52+
### TC ###
53+
tc = [
54+
([1,2,3,4], [1,4,2,3]),
55+
([1,2,3,4,5], [1,5,2,4,3])
56+
]
57+
58+
sol = Solution()
59+
for i, (l, e) in enumerate(tc, 1):
60+
r = linked_list_to_list(sol.reorderList(build_linked_list(l)))
61+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

0 commit comments

Comments
 (0)