Skip to content

Commit 025c767

Browse files
authored
Added tasks 429, 430, 432, 433.
1 parent f68befc commit 025c767

File tree

14 files changed

+569
-0
lines changed

14 files changed

+569
-0
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,7 @@ implementation 'com.github.javadev:leetcode-in-kotlin:1.7'
318318

319319
| <!-- --> | <!-- --> | <!-- --> | <!-- --> | <!-- --> | <!-- -->
320320
|-|-|-|-|-|-
321+
| 0429 |[N-ary Tree Level Order Traversal](src/main/kotlin/g0401_0500/s0429_n_ary_tree_level_order_traversal/Solution.kt)| |||
321322

322323
#### Day 10
323324

@@ -449,6 +450,7 @@ implementation 'com.github.javadev:leetcode-in-kotlin:1.7'
449450

450451
| <!-- --> | <!-- --> | <!-- --> | <!-- --> | <!-- --> | <!-- -->
451452
|-|-|-|-|-|-
453+
| 0433 |[Minimum Genetic Mutation](src/main/kotlin/g0401_0500/s0433_minimum_genetic_mutation/Solution.kt)| Medium | String, Hash_Table, Breadth_First_Search | 204 | 82.08
452454
| 0127 |[Word Ladder](src.save/main/kotlin/g0101_0200/s0127_word_ladder/Solution.kt)| Hard | Top_Interview_Questions, String, Hash_Table, Breadth_First_Search | 396 | 98.68
453455

454456
#### Day 13 Graph Theory
@@ -1628,6 +1630,10 @@ implementation 'com.github.javadev:leetcode-in-kotlin:1.7'
16281630
| 0494 |[Target Sum](src/main/kotlin/g0401_0500/s0494_target_sum/Solution.kt)| Medium | Top_100_Liked_Questions, Array, Dynamic_Programming, Backtracking | 308 | 89.61
16291631
| 0438 |[Find All Anagrams in a String](src/main/kotlin/g0401_0500/s0438_find_all_anagrams_in_a_string/Solution.kt)| Medium | Top_100_Liked_Questions, String, Hash_Table, Sliding_Window, Algorithm_II_Day_5_Sliding_Window, Programming_Skills_II_Day_12, Level_1_Day_12_Sliding_Window/Two_Pointer | 561 | 54.68
16301632
| 0437 |[Path Sum III](src/main/kotlin/g0401_0500/s0437_path_sum_iii/Solution.kt)| Medium | Top_100_Liked_Questions, Depth_First_Search, Tree, Binary_Tree, Level_2_Day_7_Tree | 403 | 54.12
1633+
| 0433 |[Minimum Genetic Mutation](src/main/kotlin/g0401_0500/s0433_minimum_genetic_mutation/Solution.kt)| Medium | String, Hash_Table, Breadth_First_Search, Graph_Theory_I_Day_12_Breadth_First_Search | 204 | 82.08
1634+
| 0432 |[All O\`one Data Structure](src/main/kotlin/g0401_0500/s0432_all_oone_data_structure/AllOne.kt)| Hard | Hash_Table, Design, Linked_List, Doubly_Linked_List | 1200 | 100.00
1635+
| 0430 |[Flatten a Multilevel Doubly Linked List](src/main/kotlin/g0401_0500/s0430_flatten_a_multilevel_doubly_linked_list/Solution.kt)| Medium | Depth_First_Search, Linked_List, Doubly_Linked_List | 194 | 97.44
1636+
| 0429 |[N-ary Tree Level Order Traversal](src/main/kotlin/g0401_0500/s0429_n_ary_tree_level_order_traversal/Solution.kt)| |||
16311637
| 0427 |[Construct Quad Tree](src/main/kotlin/g0401_0500/s0427_construct_quad_tree/Solution.kt)| Medium | Array, Tree, Matrix, Divide_and_Conquer | 221 | 94.74
16321638
| 0424 |[Longest Repeating Character Replacement](src/main/kotlin/g0401_0500/s0424_longest_repeating_character_replacement/Solution.kt)| Medium | String, Hash_Table, Sliding_Window, Level_1_Day_12_Sliding_Window/Two_Pointer | 288 | 84.38
16331639
| 0423 |[Reconstruct Original Digits from English](src/main/kotlin/g0401_0500/s0423_reconstruct_original_digits_from_english/Solution.kt)| Medium | String, Hash_Table, Math | 349 | 100.00
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com_github_leetcode.prev_next
2+
3+
class Node(var `val`: Int) {
4+
constructor(i: Int, node: Node?, node1: Node?, nothing: Node?) : this(i) {
5+
this.prev = node
6+
this.next = node1
7+
this.child = nothing
8+
}
9+
10+
var prev: Node? = null
11+
var next: Node? = null
12+
var child: Node? = null
13+
14+
override fun toString(): String {
15+
return "Node{val=$`val`,next=${this.next}}"
16+
}
17+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package g0401_0500.s0429_n_ary_tree_level_order_traversal
2+
3+
// #Medium #Breadth_First_Search #Tree #Programming_Skills_II_Day_9
4+
// #2022_12_22_Time_278_ms_(75.00%)_Space_38.9_MB_(87.50%)
5+
6+
import com_github_leetcode.Node
7+
8+
/*
9+
* Definition for a Node.
10+
* class Node(var `val`: Int) {
11+
* var neighbors: List<Node?> = listOf()
12+
* }
13+
*/
14+
15+
class Solution {
16+
fun levelOrder(root: Node?) = go(listOfNotNull(root), mutableListOf())
17+
18+
private tailrec fun go(level: List<Node>, acc: MutableList<List<Int>>): List<List<Int>> =
19+
if (level.isEmpty()) acc else go(
20+
level = level.flatMap(Node::neighbors).filterNotNull(),
21+
acc = acc.apply { level.map(Node::`val`).also { add(it) } }
22+
)
23+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
429\. N-ary Tree Level Order Traversal
2+
3+
Medium
4+
5+
Given an n-ary tree, return the _level order_ traversal of its nodes' values.
6+
7+
_Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples)._
8+
9+
**Example 1:**
10+
11+
![](https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png)
12+
13+
**Input:** root = [1,null,3,2,4,null,5,6]
14+
15+
**Output:** [[1],[3,2,4],[5,6]]
16+
17+
**Example 2:**
18+
19+
![](https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png)
20+
21+
**Input:** root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
22+
23+
**Output:** [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]
24+
25+
**Constraints:**
26+
27+
* The height of the n-ary tree is less than or equal to `1000`
28+
* The total number of nodes is between <code>[0, 10<sup>4</sup>]</code>
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package g0401_0500.s0430_flatten_a_multilevel_doubly_linked_list
2+
3+
// #Medium #Depth_First_Search #Linked_List #Doubly_Linked_List
4+
// #2022_12_12_Time_194_ms_(97.44%)_Space_35.5_MB_(87.18%)
5+
6+
import com_github_leetcode.prev_next.Node
7+
8+
/*
9+
* Definition for a Node.
10+
* class Node(var `val`: Int) {
11+
* var prev: Node? = null
12+
* var next: Node? = null
13+
* var child: Node? = null
14+
* }
15+
*/
16+
17+
class Solution {
18+
fun flatten(root: Node?): Node? {
19+
var currentNode = root
20+
while (currentNode != null) {
21+
if (currentNode?.child != null) {
22+
appendToParent(currentNode, currentNode?.next)
23+
}
24+
currentNode = currentNode?.next
25+
}
26+
return root
27+
}
28+
29+
fun appendToParent(parent: Node, parentNext: Node?) {
30+
var currentNode = parent.child
31+
while (currentNode?.next != null) {
32+
if (currentNode?.child != null) {
33+
appendToParent(currentNode, currentNode?.next)
34+
}
35+
currentNode = currentNode?.next
36+
}
37+
parent?.next = parent?.child
38+
parent?.child?.prev = parent
39+
currentNode?.next = parentNext
40+
parentNext?.prev = currentNode
41+
parent?.child = null
42+
}
43+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
430\. Flatten a Multilevel Doubly Linked List
2+
3+
Medium
4+
5+
You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional **child pointer**. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a **multilevel data structure** as shown in the example below.
6+
7+
Given the `head` of the first level of the list, **flatten** the list so that all the nodes appear in a single-level, doubly linked list. Let `curr` be a node with a child list. The nodes in the child list should appear **after** `curr` and **before** `curr.next` in the flattened list.
8+
9+
Return _the_ `head` _of the flattened list. The nodes in the list must have **all** of their child pointers set to_ `null`.
10+
11+
**Example 1:**
12+
13+
![](https://assets.leetcode.com/uploads/2021/11/09/flatten11.jpg)
14+
15+
**Input:** head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
16+
17+
**Output:** [1,2,3,7,8,11,12,9,10,4,5,6]
18+
19+
**Explanation:** The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: ![](https://assets.leetcode.com/uploads/2021/11/09/flatten12.jpg)
20+
21+
**Example 2:**
22+
23+
![](https://assets.leetcode.com/uploads/2021/11/09/flatten2.1jpg)
24+
25+
**Input:** head = [1,2,null,3]
26+
27+
**Output:** [1,3,2]
28+
29+
**Explanation:** The multilevel linked list in the input is shown. After flattening the multilevel linked list it becomes: ![](https://assets.leetcode.com/uploads/2021/11/24/list.jpg)
30+
31+
**Example 3:**
32+
33+
**Input:** head = []
34+
35+
**Output:** []
36+
37+
**Explanation:** There could be empty list in the input.
38+
39+
**Constraints:**
40+
41+
* The number of Nodes will not exceed `1000`.
42+
* <code>1 <= Node.val <= 10<sup>5</sup></code>
43+
44+
**How the multilevel linked list is represented in test cases:**
45+
46+
We use the multilevel linked list from **Example 1** above:
47+
48+
1---2---3---4---5---6--NULL | 7---8---9---10--NULL | 11--12--NULL
49+
50+
The serialization of each level is as follows:
51+
52+
[1,2,3,4,5,6,null] [7,8,9,10,null] [11,12,null]
53+
54+
To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:
55+
56+
[1, 2, 3, 4, 5, 6, null] | [null, null, 7, 8, 9, 10, null] | [ null, 11, 12, null]
57+
58+
Merging the serialization of each level and removing trailing nulls we obtain:
59+
60+
[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
package g0401_0500.s0432_all_oone_data_structure
2+
3+
// #Hard #Hash_Table #Design #Linked_List #Doubly_Linked_List
4+
// #2022_12_21_Time_1200_ms_(100.00%)_Space_123.1_MB_(100.00%)
5+
6+
class AllOne {
7+
// maintain a doubly linked list of Buckets
8+
private val head: Bucket
9+
private val tail: Bucket
10+
11+
// for accessing a specific Bucket among the Bucket list in O(1) time
12+
private val countBucketMap: MutableMap<Int, Bucket?>
13+
14+
// keep track of count of keys
15+
private val keyCountMap: MutableMap<String, Int>
16+
17+
// each Bucket contains all the keys with the same count
18+
private class Bucket(var count: Int) {
19+
var keySet: MutableSet<String>
20+
var next: Bucket? = null
21+
var pre: Bucket? = null
22+
23+
init {
24+
keySet = HashSet()
25+
}
26+
}
27+
28+
/* Initialize your data structure here. */
29+
init {
30+
head = Bucket(Int.MIN_VALUE)
31+
tail = Bucket(Int.MAX_VALUE)
32+
head.next = tail
33+
tail.pre = head
34+
countBucketMap = HashMap()
35+
keyCountMap = HashMap()
36+
}
37+
38+
/* Inserts a new key <Key> with value 1. Or increments an existing key by 1. */
39+
fun inc(key: String) {
40+
if (keyCountMap.containsKey(key)) {
41+
changeKey(key, 1)
42+
} else {
43+
keyCountMap[key] = 1
44+
if (head.next!!.count != 1) {
45+
addBucketAfter(Bucket(1), head)
46+
}
47+
head.next!!.keySet.add(key)
48+
countBucketMap[1] = head.next
49+
}
50+
}
51+
52+
/* Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
53+
fun dec(key: String) {
54+
if (keyCountMap.containsKey(key)) {
55+
val count = keyCountMap[key]!!
56+
if (count == 1) {
57+
keyCountMap.remove(key)
58+
removeKeyFromBucket(countBucketMap[count], key)
59+
} else {
60+
changeKey(key, -1)
61+
}
62+
}
63+
}
64+
65+
/* Returns one of the keys with maximal value. */
66+
fun getMaxKey(): String {
67+
return if (tail.pre === head) "" else tail.pre!!.keySet.iterator().next()
68+
}
69+
70+
/* Returns one of the keys with Minimal value. */
71+
fun getMinKey(): String {
72+
return if (head.next === tail) "" else head.next!!.keySet.iterator().next()
73+
}
74+
75+
// helper function to make change on given key according to offset
76+
private fun changeKey(key: String, offset: Int) {
77+
val count = keyCountMap[key]!!
78+
keyCountMap[key] = count + offset
79+
val curBucket = countBucketMap[count]
80+
val newBucket: Bucket?
81+
if (countBucketMap.containsKey(count + offset)) {
82+
// target Bucket already exists
83+
newBucket = countBucketMap[count + offset]
84+
} else {
85+
// add new Bucket
86+
newBucket = Bucket(count + offset)
87+
countBucketMap[count + offset] = newBucket
88+
addBucketAfter(newBucket, if (offset == 1) curBucket else curBucket!!.pre)
89+
}
90+
newBucket!!.keySet.add(key)
91+
removeKeyFromBucket(curBucket, key)
92+
}
93+
94+
private fun removeKeyFromBucket(bucket: Bucket?, key: String) {
95+
bucket!!.keySet.remove(key)
96+
if (bucket.keySet.isEmpty()) {
97+
removeBucketFromList(bucket)
98+
countBucketMap.remove(bucket.count)
99+
}
100+
}
101+
102+
private fun removeBucketFromList(bucket: Bucket?) {
103+
bucket!!.pre!!.next = bucket.next
104+
bucket.next!!.pre = bucket.pre
105+
bucket.next = null
106+
bucket.pre = null
107+
}
108+
109+
// add newBucket after preBucket
110+
private fun addBucketAfter(newBucket: Bucket, preBucket: Bucket?) {
111+
newBucket.pre = preBucket
112+
newBucket.next = preBucket!!.next
113+
preBucket.next!!.pre = newBucket
114+
preBucket.next = newBucket
115+
}
116+
}
117+
118+
/*
119+
* Your AllOne object will be instantiated and called as such:
120+
* var obj = AllOne()
121+
* obj.inc(key)
122+
* obj.dec(key)
123+
* var param_3 = obj.getMaxKey()
124+
* var param_4 = obj.getMinKey()
125+
*/
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
432\. All O\`one Data Structure
2+
3+
Hard
4+
5+
Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts.
6+
7+
Implement the `AllOne` class:
8+
9+
* `AllOne()` Initializes the object of the data structure.
10+
* `inc(String key)` Increments the count of the string `key` by `1`. If `key` does not exist in the data structure, insert it with count `1`.
11+
* `dec(String key)` Decrements the count of the string `key` by `1`. If the count of `key` is `0` after the decrement, remove it from the data structure. It is guaranteed that `key` exists in the data structure before the decrement.
12+
* `getMaxKey()` Returns one of the keys with the maximal count. If no element exists, return an empty string `""`.
13+
* `getMinKey()` Returns one of the keys with the minimum count. If no element exists, return an empty string `""`.
14+
15+
**Example 1:**
16+
17+
**Input**
18+
19+
["AllOne", "inc", "inc", "getMaxKey", "getMinKey", "inc", "getMaxKey", "getMinKey"]
20+
[[], ["hello"], ["hello"], [], [], ["leet"], [], []]
21+
22+
**Output:** [null, null, null, "hello", "hello", null, "hello", "leet"]
23+
24+
**Explanation:**
25+
26+
AllOne allOne = new AllOne();
27+
allOne.inc("hello");
28+
allOne.inc("hello");
29+
allOne.getMaxKey(); // return "hello"
30+
allOne.getMinKey(); // return "hello"
31+
allOne.inc("leet");
32+
allOne.getMaxKey(); // return "hello"
33+
allOne.getMinKey(); // return "leet"
34+
35+
**Constraints:**
36+
37+
* `1 <= key.length <= 10`
38+
* `key` consists of lowercase English letters.
39+
* It is guaranteed that for each call to `dec`, `key` is existing in the data structure.
40+
* At most <code>5 * 10<sup>4</sup></code> calls will be made to `inc`, `dec`, `getMaxKey`, and `getMinKey`.

0 commit comments

Comments
 (0)