Skip to content

Commit 8894802

Browse files
committed
Add solutions to some new problems
69. Sqrt(x) 437. Path Sum III 662. Maximum Width of Binary Tree 540. Single Element in a Sorted Array 463. Island Perimeter 167. Two Sum II - Input Array Is Sorted 57. Insert Interval 1457. Pseudo-Palindromic Paths in a Binary Tree 1325. Delete Leaves With a Given Value
1 parent 352f49c commit 8894802

File tree

63 files changed

+1289
-515
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

63 files changed

+1289
-515
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ This project are curated resources and notes of basic/fundamental/popular data s
2020
- [Greedy](./topics/greedy.md)
2121
- [Backtracking](./topics/backtracking.md)
2222
- [Hash Table](./topics/hash-table.md)
23-
- [Searching](./topics/searching.md)
23+
- [Binary Search](./topics/binary-search.md)
2424
- [Sorting](./topics/sorting.md)
2525
- (TODO) [Other](./topics/other.md)
2626
- 👉 [Problems & Solutions](./topics/problems-solutions.md)

leetcode/100.same-tree.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ fun isSameTree(p: TreeNode?, q: TreeNode?): Boolean {
88
}
99
```
1010

11+
* **Time Complexity**: `O(min(|P|, |Q|))`, where `|P|` and `|Q|` are the number of tree nodes of `p` and `q`.
12+
* **Space Complexity**: `O(min(|P|, |Q|))`
13+
1114
### Traversal
1215
```kotlin
1316
class Solution {
Lines changed: 29 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,6 @@
11
## [102. Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)
22

3-
```kotlin
4-
class Solution {
5-
6-
data class MyNode(
7-
val node: TreeNode,
8-
val level: Int
9-
)
10-
11-
private val results = mutableListOf<MutableList<Int>>()
12-
13-
fun levelOrder(root: TreeNode?): List<List<Int>> {
14-
val queue = ArrayDeque<MyNode>()
15-
if (root == null) return emptyList()
16-
queue.addLast(MyNode(root, 0))
17-
while (!queue.isEmpty()) {
18-
val myNode = queue.removeFirst()
19-
if (myNode.node.left != null) queue.addLast(MyNode(myNode.node.left, myNode.level + 1))
20-
if (myNode.node.right != null) queue.addLast(MyNode(myNode.node.right, myNode.level + 1))
21-
22-
if (results.size < myNode.level + 1) {
23-
results.add(mutableListOf<Int>())
24-
}
25-
results[myNode.level].add(myNode.node.`val`)
26-
}
27-
return results
28-
}
29-
}
30-
```
31-
32-
Solution without addition `level` variable:
33-
3+
### Iterative
344
```kotlin
355
fun levelOrder(root: TreeNode?): List<List<Int>> {
366
if (root == null) return emptyList()
@@ -52,4 +22,31 @@ fun levelOrder(root: TreeNode?): List<List<Int>> {
5222
}
5323
return results
5424
}
55-
```
25+
```
26+
27+
## Recursive
28+
```kotlin
29+
val results = mutableListOf<MutableList<Int>>()
30+
31+
fun levelOrder(root: TreeNode?): List<List<Int>> {
32+
traversal(root, 0)
33+
return results
34+
}
35+
36+
private fun traversal(root: TreeNode?, level: Int) {
37+
if (root == null) return
38+
val nodes = results.getOrNull(level)
39+
if (nodes == null) {
40+
val list = mutableListOf<Int>()
41+
list.add(root.`val`)
42+
results.add(list)
43+
} else {
44+
results[level].add(root.`val`)
45+
}
46+
traversal(root.left, level + 1)
47+
traversal(root.right, level + 1)
48+
}
49+
```
50+
51+
* **Time Complexity**: `O(n)`.
52+
* **Space Complexity**: `O(n)`.

leetcode/1091.shortest-path-in-binary-matrix.md

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,20 +13,18 @@ private val directions = arrayOf(
1313
)
1414

1515
fun shortestPathBinaryMatrix(grid: Array<IntArray>): Int {
16-
val infinite = Int.MAX_VALUE / 2
1716
val n = grid.size
18-
if (grid[0][0] == 1 || grid[n -1][n - 1] == 1) return -1
17+
if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) return -1
1918

20-
val distances = Array(n) { _ -> IntArray(n) { _ -> infinite }}
19+
val distances = Array(n) { _ -> IntArray(n) { _ -> Int.MAX_VALUE }}
2120
val queue = ArrayDeque<Pair<Int, Int>>()
2221
queue.add(0 to 0)
23-
visited.add(0 to 0)
2422
distances[0][0] = 1
2523
while (!queue.isEmpty()) {
2624
val node = queue.removeFirst()
2725
val x = node.first
2826
val y = node.second
29-
if (x == n -1 && y == n - 1) return distances[x][y]
27+
if (x == n - 1 && y == n - 1) return distances[x][y]
3028
directions.forEach { d ->
3129
val newX = x + d[0]
3230
val newY = y + d[1]
@@ -42,3 +40,6 @@ fun shortestPathBinaryMatrix(grid: Array<IntArray>): Int {
4240
return -1
4341
}
4442
```
43+
44+
* **Time Complexity**: `O(n^2)`.
45+
* **Space Complexity**: `O(n^2)`.

leetcode/110.balanced-binary-tree.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,12 @@ private fun max(n1: Int, n2: Int) = if (n1 > n2) n1 else n2
2121
```
2222

2323
* **Time Complexity**: Calculate the height = `O(lg n)`, and we have to calculate every node `n`, the average case (every node has children) is `O(n lg n)`, but the worst case is `O(n^2)` when the tree is skewed because the height becomes `O(n)`.
24+
* **Space Complexity**: `O(n)`.
2425

2526
> We can calculate the height and store it, then traversal to check. That would be `O(n)` time and space complexity.
2627
2728
### Bottom-Up Solution (Optimal)
28-
* We traverse all nodes in postorder, and determine if it's balanced of its child nodes, then check the current node.
29+
* We calculate the height (left and right) and check if it is balanced at the same function call, and if it's not balanced then return -1 to indicate unbalanced.
2930
* If it's not balanced from its child node, then it's not balanced as well for the current node.
3031

3132
![](../media/110.balanced-binary-tree.png)
@@ -46,6 +47,7 @@ private fun getHeight(root: TreeNode?): Int {
4647
}
4748
```
4849
* **Time Complexity**: It becomes `O(n)` since we calculate the height only once for every node.
50+
* **Space Complexity**: `O(n)`.
4951

5052
### My Solution (Accepted)
5153
```kotlin

leetcode/112.path-sum.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,7 @@ fun hasPathSum(root: TreeNode?, targetSum: Int): Boolean {
88
return hasPathSum(root.left, targetSum - root.`val`) || hasPathSum(root.right, targetSum - root.`val`)
99
}
1010
}
11-
```
11+
```
12+
13+
* **Time Complexity**: `O(n)`.
14+
* **Space Complexity**: `O(n)`.

leetcode/113.path-sum-ii.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,8 @@ private fun dfs(root: TreeNode?, targetSum: Int, path: MutableList<Int>) {
2929
path.removeAt(path.size - 1)
3030
}
3131
}
32-
```
32+
```
33+
34+
> Not fully understand.
35+
* **Time Complexity**: `O(n^2)`? https://leetcode.cn/problems/path-sum-ii/solution/lu-jing-zong-he-ii-by-leetcode-solution/, but why?
36+
* **Space Complexity**: `O(n)` for recursive call stack.

leetcode/116.populating-next-right-pointers-in-each-node.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,10 @@ fun connect(root: Node?): Node? {
1818
}
1919
```
2020

21+
* **Time Complexity**: `O(n)`.
22+
* **Space Complexity**: `O(n)`.
23+
24+
### Space Optimal
25+
> TODO: `O(1)` space complexity.
26+
2127
> Take a look at another solution (using the `next` pointer just built): https://leetcode.cn/problems/populating-next-right-pointers-in-each-node/solution/tian-chong-mei-ge-jie-dian-de-xia-yi-ge-you-ce-2-4/

leetcode/128.longest-consecutive-sequence.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ fun longestConsecutive(nums: IntArray): Int {
1515
for (i in 0 until nums.size) {
1616
val num = nums[i]
1717
// This is the key, we only check ascending direction.
18+
// We're looking for the start sequence and it has not "left number" (num - 1)
19+
1820
// If we have num - 1 which is consecutive to num, answer will check at num - 1 iteration, not current iteration.
1921
if (!hashSet.contains(num - 1)) {
2022
var next = num + 1
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
## [1325. Delete Leaves With a Given Value](https://leetcode.com/problems/delete-leaves-with-a-given-value)
2+
3+
### Recursive
4+
For problem statement `Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted`, so we have to process the child first, when we've done, we check the root to see if that becomes the leaf and if to delete or not. (Postorder)
5+
6+
```kotlin
7+
fun removeLeafNodes(root: TreeNode?, target: Int): TreeNode? {
8+
if (root == null) return null
9+
root.left = removeLeafNodes(root.left, target)
10+
root.right = removeLeafNodes(root.right, target)
11+
12+
if (root.left == null && root.right == null && root.`val` == target) {
13+
return null
14+
}
15+
return root
16+
}
17+
```
18+
* **Time Complexity**: `O(n)`.
19+
* **Space Complexity**: `O(h)`.
20+
21+
22+
### Iterative
23+
```kotlin
24+
fun removeLeafNodes(root: TreeNode?, target: Int): TreeNode? {
25+
if (root == null) return null
26+
val parentMap = hashMapOf<TreeNode, TreeNode>()
27+
val queue = ArrayDeque<TreeNode>()
28+
val leafs = mutableListOf<TreeNode>()
29+
queue.addLast(root)
30+
while (queue.isNotEmpty()) {
31+
val node = queue.removeFirst()
32+
if (node.left == null && node.right == null) {
33+
leafs.add(node)
34+
continue
35+
}
36+
if (node.left != null) {
37+
queue.addLast(node.left)
38+
parentMap[node.left] = node
39+
}
40+
if (node.right != null) {
41+
queue.addLast(node.right)
42+
parentMap[node.right] = node
43+
}
44+
}
45+
46+
for (leaf in leafs) {
47+
var current = leaf
48+
var parent = parentMap[current]
49+
while (current.`val` == target && current.left == null && current.right == null) {
50+
if (parent == null) return null
51+
52+
if (current == parent!!.left) parent!!.left = null
53+
else parent!!.right = null
54+
55+
current = parent!!
56+
parent = parentMap[parent!!]
57+
}
58+
}
59+
return root
60+
}
61+
```
62+
63+
* **Time Complexity**: `O(n)`.
64+
* **Space Complexity**: `O(n)`.

0 commit comments

Comments
 (0)