Skip to content

Commit 8da7577

Browse files
committed
feat(python): solutions
1 parent eb18eba commit 8da7577

18 files changed

+701
-14
lines changed

JavaScript/0387. First Unique Character in a String.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@ const firstUniqChar = (s) => {
3030
const map = {};
3131

3232
for (const c of s) {
33-
if (map[c] == null) map[c] = 1;
34-
else map[c]++;
33+
if (map[c] == null) map[c] = 0;
34+
map[c]++;
3535
}
3636

3737
for (let i = 0; i < s.length; i++) {

Python/0101. Symmetric Tree.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,11 @@ def isSymmetric(self, root: Optional[TreeNode]) -> bool:
3535
def isMirror(l: Optional[TreeNode], r: Optional[TreeNode]) -> bool:
3636
if not l and not r:
3737
return True
38-
if not l or not r:
38+
elif not l or not r:
3939
return False
40-
if l.val != r.val:
40+
elif l.val != r.val:
4141
return False
42-
return isMirror(l.left, r.right) and isMirror(l.right, r.left)
42+
else:
43+
return isMirror(l.left, r.right) and isMirror(l.right, r.left)
4344

4445
return isMirror(root.left, root.right)

Python/0105. Construct Binary Tree from Preorder and Inorder Traversal.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,22 @@
3636
# 9 20
3737
# / \
3838
# 15 7
39+
40+
41+
# Similar
42+
# 105. Construct Binary Tree from Preorder and Inorder Traversal
43+
# 106. Construct Binary Tree from Inorder and Postorder Traversal
44+
class Solution:
45+
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
46+
if not preorder or not inorder:
47+
return None
48+
root = TreeNode(preorder[0])
49+
root_idx = inorder.index(preorder[0])
50+
root.left = self.buildTree(preorder[1 : root_idx + 1], inorder[:root_idx])
51+
root.right = self.buildTree(preorder[root_idx + 1 :], inorder[root_idx + 1 :])
52+
return root
53+
54+
3955
class Solution:
4056
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
4157
if not preorder or not inorder:
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.
2+
#
3+
# Example 1:
4+
#
5+
# Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
6+
# Output: [3,9,20,null,null,15,7]
7+
#
8+
# Example 2:
9+
#
10+
# Input: inorder = [-1], postorder = [-1]
11+
# Output: [-1]
12+
#
13+
# Constraints:
14+
#
15+
# 1 <= inorder.length <= 3000
16+
# postorder.length == inorder.length
17+
# -3000 <= inorder[i], postorder[i] <= 3000
18+
# inorder and postorder consist of unique values.
19+
# Each value of postorder also appears in inorder.
20+
# inorder is guaranteed to be the inorder traversal of the tree.
21+
# postorder is guaranteed to be the postorder traversal of the tree.
22+
23+
24+
# Definition for a binary tree node.
25+
# class TreeNode:
26+
# def __init__(self, val=0, left=None, right=None):
27+
# self.val = val
28+
# self.left = left
29+
# self.right = right
30+
31+
# Similar
32+
# 105. Construct Binary Tree from Preorder and Inorder Traversal
33+
# 106. Construct Binary Tree from Inorder and Postorder Traversal
34+
class Solution:
35+
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
36+
if not inorder or not postorder:
37+
return None
38+
root = TreeNode(postorder[-1])
39+
root_idx = inorder.index(postorder[-1])
40+
root.left = self.buildTree(inorder[:root_idx], postorder[:root_idx])
41+
root.right = self.buildTree(inorder[root_idx + 1 :], postorder[root_idx:-1])
42+
return root

Python/0112. Path Sum.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
2+
# A leaf is a node with no children.
3+
#
4+
# Example 1:
5+
#
6+
# Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
7+
# Output: true
8+
# Explanation: The root-to-leaf path with the target sum is shown.
9+
#
10+
# Example 2:
11+
#
12+
# Input: root = [1,2,3], targetSum = 5
13+
# Output: false
14+
# Explanation: There two root-to-leaf paths in the tree:
15+
# (1 --> 2): The sum is 3.
16+
# (1 --> 3): The sum is 4.
17+
# There is no root-to-leaf path with sum = 5.
18+
#
19+
# Example 3:
20+
#
21+
# Input: root = [], targetSum = 0
22+
# Output: false
23+
# Explanation: Since the tree is empty, there are no root-to-leaf paths.
24+
#
25+
# Constraints:
26+
#
27+
# The number of nodes in the tree is in the range [0, 5000].
28+
# -1000 <= Node.val <= 1000
29+
# -1000 <= targetSum <= 1000
30+
31+
32+
# Definition for a binary tree node.
33+
# class TreeNode:
34+
# def __init__(self, val=0, left=None, right=None):
35+
# self.val = val
36+
# self.left = left
37+
# self.right = right
38+
class Solution:
39+
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
40+
if not root:
41+
return False
42+
if not root.left and not root.right:
43+
return root.val == targetSum
44+
return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(
45+
root.right, targetSum - root.val
46+
)

Python/0116. Populating Next Right Pointers in Each Node.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ def connect(self, root: "Optional[Node]") -> "Optional[Node]":
6262
# Similar
6363
# 102. Binary Tree Level Order Traversal
6464
# 116. Populating Next Right Pointers in Each Node
65+
# 117. Populating Next Right Pointers in Each Node II
6566
#
6667
# Time O(n)
6768
class Solution:
@@ -70,13 +71,13 @@ def connect(self, root: "Optional[Node]") -> "Optional[Node]":
7071
return None
7172

7273
q = [root]
73-
7474
while q:
7575
nodes = q.copy()
7676
q = []
7777
while nodes:
7878
node = nodes.pop(0)
79-
node.next = nodes[0] if nodes else None
79+
if nodes:
80+
node.next = nodes[0]
8081
if node.left:
8182
q.append(node.left)
8283
if node.right:
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# Given a binary tree
2+
#
3+
# struct Node {
4+
# int val;
5+
# Node *left;
6+
# Node *right;
7+
# Node *next;
8+
# }
9+
#
10+
# Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
11+
#
12+
# Initially, all next pointers are set to NULL.
13+
#
14+
# Example 1:
15+
#
16+
# Input: root = [1,2,3,4,5,null,7]
17+
# Output: [1,#,2,3,#,4,5,7,#]
18+
# Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
19+
#
20+
# Example 2:
21+
#
22+
# Input: root = []
23+
# Output: []
24+
#
25+
# Constraints:
26+
#
27+
# The number of nodes in the tree is in the range [0, 6000].
28+
# -100 <= Node.val <= 100
29+
#
30+
# Follow-up:
31+
#
32+
# You may only use constant extra space.
33+
# The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
34+
35+
"""
36+
# Definition for a Node.
37+
class Node:
38+
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
39+
self.val = val
40+
self.left = left
41+
self.right = right
42+
self.next = next
43+
"""
44+
45+
# Similar
46+
# 116. Populating Next Right Pointers in Each Node
47+
# 117. Populating Next Right Pointers in Each Node II
48+
class Solution:
49+
def connect(self, root: "Node") -> "Node":
50+
if not root:
51+
return root
52+
53+
q = [root]
54+
while q:
55+
nodes = q.copy()
56+
q = []
57+
while nodes:
58+
node = nodes.pop(0)
59+
if nodes:
60+
node.next = nodes[0]
61+
if node.left:
62+
q.append(node.left)
63+
if node.right:
64+
q.append(node.right)
65+
return root
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Given the root of a binary tree, return the number of uni-value subtrees.
2+
# A uni-value subtree means all nodes of the subtree have the same value.
3+
#
4+
# Example 1:
5+
#
6+
# Input: root = [5,1,5,5,5,null,5]
7+
# Output: 4
8+
#
9+
# Example 2:
10+
#
11+
# Input: root = []
12+
# Output: 0
13+
#
14+
# Example 3:
15+
#
16+
# Input: root = [5,5,5,5,5,null,5]
17+
# Output: 6
18+
#
19+
# Constraints:
20+
#
21+
# The number of the node in the tree will be in the range [0, 1000].
22+
# -1000 <= Node.val <= 1000
23+
24+
25+
# Definition for a binary tree node.
26+
# class TreeNode:
27+
# def __init__(self, val=0, left=None, right=None):
28+
# self.val = val
29+
# self.left = left
30+
# self.right = right
31+
class Solution:
32+
def countUnivalSubtrees(self, root: Optional[TreeNode]) -> int:
33+
if not root:
34+
return 0
35+
self.count = 0
36+
self.is_univalue_subtree(root)
37+
return self.count
38+
39+
def is_univalue_subtree(self, root):
40+
if not root:
41+
return True
42+
l = self.is_univalue_subtree(root.left)
43+
r = self.is_univalue_subtree(root.right)
44+
if l and r:
45+
if root.left and root.left.val != root.val:
46+
return False
47+
if root.right and root.right.val != root.val:
48+
return False
49+
self.count += 1
50+
return True
51+
return False
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix.
2+
# Note that it is the kth smallest element in the sorted order, not the kth distinct element.
3+
# You must find a solution with a memory complexity better than O(n2).
4+
#
5+
# Example 1:
6+
#
7+
# Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
8+
# Output: 13
9+
# Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13
10+
#
11+
# Example 2:
12+
#
13+
# Input: matrix = [[-5]], k = 1
14+
# Output: -5
15+
#
16+
# Constraints:
17+
#
18+
# n == matrix.length == matrix[i].length
19+
# 1 <= n <= 300
20+
# -109 <= matrix[i][j] <= 109
21+
# All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order.
22+
# 1 <= k <= n2
23+
#
24+
# Follow up:
25+
#
26+
# Could you solve the problem with a constant memory (i.e., O(1) memory complexity)?
27+
# Could you solve the problem in O(n) time complexity? The solution may be too advanced for an interview but you may find reading this paper fun.
28+
29+
30+
# 1)
31+
class Solution:
32+
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
33+
n = len(matrix)
34+
l, r = matrix[0][0], matrix[-1][-1]
35+
while l < r:
36+
m = (l + r) // 2
37+
if self.count_less_equal(matrix, m) < k:
38+
l = m + 1
39+
else:
40+
r = m
41+
return l
42+
43+
def count_less_equal(self, matrix, target):
44+
n = len(matrix)
45+
count = 0
46+
for i in range(n):
47+
for j in range(n):
48+
if matrix[i][j] <= target:
49+
count += 1
50+
return count
51+
52+
53+
# 2) Optimized version of 1)
54+
class Solution:
55+
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
56+
n = len(matrix)
57+
l, r = matrix[0][0], matrix[-1][-1]
58+
while l < r:
59+
m = (l + r) // 2
60+
if self.count_less_equal(matrix, m) < k:
61+
l = m + 1
62+
else:
63+
r = m
64+
return l
65+
66+
def count_less_equal(self, matrix, target):
67+
n = len(matrix)
68+
count = 0
69+
i = n - 1
70+
j = 0
71+
while i >= 0 and j < n:
72+
if matrix[i][j] <= target:
73+
count += i + 1
74+
j += 1
75+
else:
76+
i -= 1
77+
return count

0 commit comments

Comments
 (0)