File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments