Skip to content

Commit b92daec

Browse files
Jeehay28Jeehay28
authored andcommitted
Add merge-k-sorted-lists solution in TS
1 parent c1af8ba commit b92daec

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

merge-k-sorted-lists/Jeehay28.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class ListNode {
2+
val: number;
3+
next: ListNode | null;
4+
constructor(val?: number, next?: ListNode | null) {
5+
this.val = val === undefined ? 0 : val;
6+
this.next = next === undefined ? null : next;
7+
}
8+
}
9+
10+
// TC: O(n * log n), n = total number of all nodes combined (across all lists)
11+
// SC: O(n)
12+
// TDDO: Implement more optimized solution using Min Heap with TC: O(n log k)
13+
function mergeKLists(lists: Array<ListNode | null>): ListNode | null {
14+
const nodeValues: number[] = [];
15+
16+
for (let node of lists) {
17+
while (node) {
18+
nodeValues.push(node.val);
19+
node = node.next;
20+
}
21+
}
22+
23+
nodeValues.sort((a, b) => a - b);
24+
25+
if (nodeValues.length === 0) return null;
26+
27+
const head = new ListNode(nodeValues[0]);
28+
let temp = head;
29+
30+
for (let i = 1; i < nodeValues.length; i++) {
31+
temp.next = new ListNode(nodeValues[i]);
32+
temp = temp.next;
33+
}
34+
35+
return head;
36+
}
37+

0 commit comments

Comments
 (0)