Skip to content

Commit 9dd3b91

Browse files
authored
Added tasks 129-135
1 parent f995bf5 commit 9dd3b91

File tree

15 files changed

+453
-0
lines changed

15 files changed

+453
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# #Medium #Depth_First_Search #Tree #Binary_Tree #Top_Interview_150_Binary_Tree_General
2+
# #2025_09_14_Time_0_ms_(100.00%)_Space_17.98_MB_(15.68%)
3+
4+
from typing import Optional
5+
6+
class TreeNode:
7+
def __init__(self, val=0, left=None, right=None):
8+
self.val = val
9+
self.left = left
10+
self.right = right
11+
12+
class Solution:
13+
def __init__(self):
14+
self.sum_total = 0
15+
16+
def sumNumbers(self, root: Optional[TreeNode]) -> int:
17+
self._recurseSum(root, 0)
18+
return self.sum_total
19+
20+
def _recurseSum(self, node: Optional[TreeNode], cur_num: int):
21+
if node.left is None and node.right is None:
22+
self.sum_total += 10 * cur_num + node.val
23+
else:
24+
if node.left is not None:
25+
self._recurseSum(node.left, 10 * cur_num + node.val)
26+
if node.right is not None:
27+
self._recurseSum(node.right, 10 * cur_num + node.val)
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import unittest
2+
from Solution0129 import Solution, TreeNode
3+
4+
class SolutionTest(unittest.TestCase):
5+
def test_sumNumbers(self):
6+
root = TreeNode(1)
7+
root.left = TreeNode(2)
8+
root.right = TreeNode(3)
9+
self.assertEqual(Solution().sumNumbers(root), 25)
10+
11+
def test_sumNumbers2(self):
12+
root = TreeNode(4)
13+
root.left = TreeNode(9)
14+
root.right = TreeNode(0)
15+
root.left.left = TreeNode(5)
16+
root.left.right = TreeNode(1)
17+
self.assertEqual(Solution().sumNumbers(root), 1026)
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
129\. Sum Root to Leaf Numbers
2+
3+
Medium
4+
5+
You are given the `root` of a binary tree containing digits from `0` to `9` only.
6+
7+
Each root-to-leaf path in the tree represents a number.
8+
9+
* For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`.
10+
11+
Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer.
12+
13+
A **leaf** node is a node with no children.
14+
15+
**Example 1:**
16+
17+
![](https://assets.leetcode.com/uploads/2021/02/19/num1tree.jpg)
18+
19+
**Input:** root = [1,2,3]
20+
21+
**Output:** 25
22+
23+
**Explanation:** The root-to-leaf path `1->2` represents the number `12`. The root-to-leaf path `1->3` represents the number `13`. Therefore, sum = 12 + 13 = `25`.
24+
25+
**Example 2:**
26+
27+
![](https://assets.leetcode.com/uploads/2021/02/19/num2tree.jpg)
28+
29+
**Input:** root = [4,9,0,5,1]
30+
31+
**Output:** 1026
32+
33+
**Explanation:** The root-to-leaf path `4->9->5` represents the number 495. The root-to-leaf path `4->9->1` represents the number 491. The root-to-leaf path `4->0` represents the number 40. Therefore, sum = 495 + 491 + 40 = `1026`.
34+
35+
**Constraints:**
36+
37+
* The number of nodes in the tree is in the range `[1, 1000]`.
38+
* `0 <= Node.val <= 9`
39+
* The depth of the tree will not exceed `10`.
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# #Medium #Top_Interview_Questions #Array #Depth_First_Search #Breadth_First_Search #Matrix
2+
# #Union_Find #Algorithm_II_Day_8_Breadth_First_Search_Depth_First_Search
3+
# #Top_Interview_150_Graph_General #2025_09_14_Time_3_ms_(86.86%)_Space_21.58_MB_(88.48%)
4+
5+
from typing import List
6+
7+
class Solution:
8+
def solve(self, board: List[List[str]]) -> None:
9+
# Edge case, empty grid
10+
if not board:
11+
return
12+
# Traverse first and last rows (boundaries)
13+
for i in range(len(board[0])):
14+
# first row
15+
if board[0][i] == 'O':
16+
# It will convert O and all it's touching O's to #
17+
self._dfs(board, 0, i)
18+
# last row
19+
if board[len(board) - 1][i] == 'O':
20+
# Converts O's to #'s (same thing as above)
21+
self._dfs(board, len(board) - 1, i)
22+
# Traverse first and last Column (boundaries)
23+
for i in range(len(board)):
24+
# first Column
25+
if board[i][0] == 'O':
26+
# Converts O's to #'s
27+
self._dfs(board, i, 0)
28+
# last Column
29+
if board[i][len(board[0]) - 1] == 'O':
30+
# Converts O's to #'s
31+
self._dfs(board, i, len(board[0]) - 1)
32+
# Traverse through entire matrix
33+
for i in range(len(board)):
34+
for j in range(len(board[0])):
35+
if board[i][j] == 'O':
36+
# Convert O's to X's
37+
board[i][j] = 'X'
38+
if board[i][j] == '#':
39+
# Convert #'s to O's
40+
board[i][j] = 'O'
41+
42+
def _dfs(self, board: List[List[str]], row: int, column: int):
43+
if (row < 0 or row >= len(board) or column < 0 or
44+
column >= len(board[0]) or board[row][column] != 'O'):
45+
return
46+
board[row][column] = '#'
47+
self._dfs(board, row + 1, column)
48+
self._dfs(board, row - 1, column)
49+
self._dfs(board, row, column + 1)
50+
self._dfs(board, row, column - 1)
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import unittest
2+
from Solution0130 import Solution
3+
4+
class SolutionTest(unittest.TestCase):
5+
def test_solve(self):
6+
board = [
7+
['X', 'X', 'X', 'X'],
8+
['X', 'O', 'O', 'X'],
9+
['X', 'X', 'O', 'X'],
10+
['X', 'O', 'X', 'X']
11+
]
12+
Solution().solve(board)
13+
expected = [
14+
['X', 'X', 'X', 'X'],
15+
['X', 'X', 'X', 'X'],
16+
['X', 'X', 'X', 'X'],
17+
['X', 'O', 'X', 'X']
18+
]
19+
self.assertEqual(board, expected)
20+
21+
def test_solve2(self):
22+
board = [['X']]
23+
Solution().solve(board)
24+
expected = [['X']]
25+
self.assertEqual(board, expected)
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
130\. Surrounded Regions
2+
3+
Medium
4+
5+
Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
6+
7+
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
8+
9+
**Example 1:**
10+
11+
![](https://assets.leetcode.com/uploads/2021/02/19/xogrid.jpg)
12+
13+
**Input:** board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
14+
15+
**Output:** [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
16+
17+
**Explanation:** Surrounded regions should not be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.
18+
19+
**Example 2:**
20+
21+
**Input:** board = [["X"]]
22+
23+
**Output:** [["X"]]
24+
25+
**Constraints:**
26+
27+
* `m == board.length`
28+
* `n == board[i].length`
29+
* `1 <= m, n <= 200`
30+
* `board[i][j]` is `'X'` or `'O'`.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# #Medium #Hash_Table #Depth_First_Search #Breadth_First_Search #Graph #Udemy_Graph
2+
# #Top_Interview_150_Graph_General #2025_09_14_Time_38_ms_(86.28%)_Space_17.94_MB_(97.41%)
3+
4+
from typing import Dict, List, Optional
5+
6+
class Node:
7+
def __init__(self, val=0, neighbors=None):
8+
self.val = val
9+
self.neighbors = neighbors if neighbors is not None else []
10+
11+
class Solution:
12+
def cloneGraph(self, node: Optional[Node]) -> Optional[Node]:
13+
return self._cloneGraph(node, {})
14+
15+
def _cloneGraph(self, node: Optional[Node], processed_nodes: Dict[Node, Node]) -> Optional[Node]:
16+
if node is None:
17+
return None
18+
elif node in processed_nodes:
19+
return processed_nodes[node]
20+
new_node = Node()
21+
processed_nodes[node] = new_node
22+
new_node.val = node.val
23+
new_node.neighbors = []
24+
for neighbor in node.neighbors:
25+
cloned_neighbor = self._cloneGraph(neighbor, processed_nodes)
26+
if cloned_neighbor is not None:
27+
new_node.neighbors.append(cloned_neighbor)
28+
return new_node
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import unittest
2+
from Solution0133 import Solution, Node
3+
4+
class SolutionTest(unittest.TestCase):
5+
def test_cloneGraph(self):
6+
node1 = Node(1)
7+
node2 = Node(2)
8+
node3 = Node(3)
9+
node4 = Node(4)
10+
node1.neighbors = [node2, node4]
11+
node2.neighbors = [node1, node3]
12+
node3.neighbors = [node2, node4]
13+
node4.neighbors = [node1, node3]
14+
15+
result = Solution().cloneGraph(node1)
16+
17+
# Check that the cloned graph has the same structure
18+
self.assertEqual(result.val, 1)
19+
self.assertEqual(len(result.neighbors), 2)
20+
self.assertEqual(result.neighbors[0].val, 2)
21+
self.assertEqual(result.neighbors[1].val, 4)
22+
23+
def test_cloneGraph2(self):
24+
node1 = Node(1)
25+
result = Solution().cloneGraph(node1)
26+
self.assertEqual(result.val, 1)
27+
self.assertEqual(len(result.neighbors), 0)
28+
29+
def test_cloneGraph3(self):
30+
self.assertIsNone(Solution().cloneGraph(None))
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
133\. Clone Graph
2+
3+
Medium
4+
5+
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
6+
7+
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
8+
9+
Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors.
10+
11+
class Node { public int val; public List<Node> neighbors; }
12+
13+
**Test case format:**
14+
15+
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list.
16+
17+
**An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
18+
19+
The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph.
20+
21+
**Example 1:**
22+
23+
![](https://assets.leetcode.com/uploads/2019/11/04/133_clone_graph_question.png)
24+
25+
**Input:** adjList = [[2,4],[1,3],[2,4],[1,3]]
26+
27+
**Output:** [[2,4],[1,3],[2,4],[1,3]]
28+
29+
**Explanation:**
30+
31+
There are 4 nodes in the graph.
32+
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
33+
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
34+
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
35+
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
36+
37+
**Example 2:**
38+
39+
![](https://assets.leetcode.com/uploads/2020/01/07/graph.png)
40+
41+
**Input:** adjList = [[]]
42+
43+
**Output:** [[]]
44+
45+
**Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
46+
47+
**Example 3:**
48+
49+
**Input:** adjList = []
50+
51+
**Output:** []
52+
53+
**Explanation:** This an empty graph, it does not have any nodes.
54+
55+
**Example 4:**
56+
57+
![](https://assets.leetcode.com/uploads/2020/01/07/graph-1.png)
58+
59+
**Input:** adjList = [[2],[1]]
60+
61+
**Output:** [[2],[1]]
62+
63+
**Constraints:**
64+
65+
* The number of nodes in the graph is in the range `[0, 100]`.
66+
* `1 <= Node.val <= 100`
67+
* `Node.val` is unique for each node.
68+
* There are no repeated edges and no self-loops in the graph.
69+
* The Graph is connected and all nodes can be visited starting from the given node.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# #Medium #Top_Interview_Questions #Array #Greedy #Top_Interview_150_Array/String
2+
# #2025_09_14_Time_15_ms_(88.80%)_Space_23.18_MB_(96.18%)
3+
4+
from typing import List
5+
6+
class Solution:
7+
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
8+
total_gas, total_cost = sum(gas), sum(cost)
9+
if total_gas < total_cost:
10+
return -1 # impossible
11+
12+
start, tank = 0, 0
13+
for i in range(len(gas)):
14+
tank += gas[i] - cost[i]
15+
if tank < 0:
16+
start = i + 1 # reset starting point
17+
tank = 0
18+
return start

0 commit comments

Comments
 (0)