Given K sorted linked lists of size N each, the task is to merge them all maintaining their sorted order.
Examples:
Input: K = 3, N = 4
list1 = 1->3->5->7->NULL
list2 = 2->4->6->8->NULL
list3 = 0->9->10->11->NULL
Output: 0->1->2->3->4->5->6->7->8->9->10->11
Merged lists in a sorted order where every element is greater than the previous element.
Input: K = 3, N = 3
list1 = 1->3->7->NULL
list2 = 2->4->8->NULL
list3 = 9->10->11->NULL
Output: 1->2->3->4->7->8->9->10->11
Merged lists in a sorted order where every element is greater than the previous element.
Naive Approach:
A Simple Solution is to initialize the result as the first list. Now traverse all lists starting from the second list. Insert every node of the currently traversed list into the result in a sorted way.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
void printList(Node* node)
{
while (node != NULL) {
printf ( "%d " , node->data);
node = node->next;
}
}
Node* mergeKLists(Node* arr[], int last)
{
for ( int i = 1; i <= last; i++) {
while ( true ) {
Node *head_0 = arr[0], *head_i = arr[i];
if (head_i == NULL)
break ;
if (head_0->data >= head_i->data) {
arr[i] = head_i->next;
head_i->next = head_0;
arr[0] = head_i;
}
else
while (head_0->next != NULL) {
if (head_0->next->data
>= head_i->data) {
arr[i] = head_i->next;
head_i->next = head_0->next;
head_0->next = head_i;
break ;
}
head_0 = head_0->next;
if (head_0->next == NULL) {
arr[i] = head_i->next;
head_i->next = NULL;
head_0->next = head_i;
head_0->next->next = NULL;
break ;
}
}
}
}
return arr[0];
}
Node* newNode( int data)
{
struct Node* temp = new Node;
temp->data = data;
temp->next = NULL;
return temp;
}
int main()
{
int k = 3;
int n = 4;
Node* arr[k];
arr[0] = newNode(1);
arr[0]->next = newNode(3);
arr[0]->next->next = newNode(5);
arr[0]->next->next->next = newNode(7);
arr[1] = newNode(2);
arr[1]->next = newNode(4);
arr[1]->next->next = newNode(6);
arr[1]->next->next->next = newNode(8);
arr[2] = newNode(0);
arr[2]->next = newNode(9);
arr[2]->next->next = newNode(10);
arr[2]->next->next->next = newNode(11);
Node* head = mergeKLists(arr, k - 1);
printList(head);
return 0;
}
|
Java
import java.io.*;
class Node {
int data;
Node next;
Node( int key)
{
data = key;
next = null ;
}
}
class GFG {
static Node head;
static Node temp;
static void printList(Node node)
{
while (node != null ) {
System.out.print(node.data + " " );
node = node.next;
}
System.out.println();
}
static Node mergeKLists(Node arr[], int last)
{
for ( int i = 1 ; i <= last; i++) {
while ( true ) {
Node head_0 = arr[ 0 ];
Node head_i = arr[i];
if (head_i == null )
break ;
if (head_0.data >= head_i.data) {
arr[i] = head_i.next;
head_i.next = head_0;
arr[ 0 ] = head_i;
}
else {
while (head_0.next != null ) {
if (head_0.next.data
>= head_i.data) {
arr[i] = head_i.next;
head_i.next = head_0.next;
head_0.next = head_i;
break ;
}
head_0 = head_0.next;
if (head_0.next == null ) {
arr[i] = head_i.next;
head_i.next = null ;
head_0.next = head_i;
head_0.next.next = null ;
break ;
}
}
}
}
}
return arr[ 0 ];
}
public static void main(String[] args)
{
int k = 3 ;
int n = 4 ;
Node[] arr = new Node[k];
arr[ 0 ] = new Node( 1 );
arr[ 0 ].next = new Node( 3 );
arr[ 0 ].next.next = new Node( 5 );
arr[ 0 ].next.next.next = new Node( 7 );
arr[ 1 ] = new Node( 2 );
arr[ 1 ].next = new Node( 4 );
arr[ 1 ].next.next = new Node( 6 );
arr[ 1 ].next.next.next = new Node( 8 );
arr[ 2 ] = new Node( 0 );
arr[ 2 ].next = new Node( 9 );
arr[ 2 ].next.next = new Node( 10 );
arr[ 2 ].next.next.next = new Node( 11 );
head = mergeKLists(arr, k - 1 );
printList(head);
}
}
|
Python3
class Node:
def __init__( self , x):
self .data = x
self . next = None
def printList(node):
while (node ! = None ):
print (node.data,
end = " " )
node = node. next
def mergeKLists(arr, last):
for i in range ( 1 , last + 1 ):
while ( True ):
head_0 = arr[ 0 ]
head_i = arr[i]
if (head_i = = None ):
break
if (head_0.data > =
head_i.data):
arr[i] = head_i. next
head_i. next = head_0
arr[ 0 ] = head_i
else :
while (head_0. next ! = None ):
if (head_0. next .data > =
head_i.data):
arr[i] = head_i. next
head_i. next = head_0. next
head_0. next = head_i
break
head_0 = head_0. next
if (head_0. next = = None ):
arr[i] = head_i. next
head_i. next = None
head_0. next = head_i
head_0. next . next = None
break
return arr[ 0 ]
if __name__ = = '__main__' :
k = 3
n = 4
arr = [ None for i in range (k)]
arr[ 0 ] = Node( 1 )
arr[ 0 ]. next = Node( 3 )
arr[ 0 ]. next . next = Node( 5 )
arr[ 0 ]. next . next . next = Node( 7 )
arr[ 1 ] = Node( 2 )
arr[ 1 ]. next = Node( 4 )
arr[ 1 ]. next . next = Node( 6 )
arr[ 1 ]. next . next . next = Node( 8 )
arr[ 2 ] = Node( 0 )
arr[ 2 ]. next = Node( 9 )
arr[ 2 ]. next . next = Node( 10 )
arr[ 2 ]. next . next . next = Node( 11 )
head = mergeKLists(arr, k - 1 )
printList(head)
|
C#
using System;
public class Node {
public int data;
public Node next;
public Node( int key)
{
data = key;
next = null ;
}
}
public class GFG {
static Node head;
static void printList(Node node)
{
while (node != null ) {
Console.Write(node.data + " " );
node = node.next;
}
Console.WriteLine();
}
static Node mergeKLists(Node[] arr, int last)
{
for ( int i = 1; i <= last; i++) {
while ( true ) {
Node head_0 = arr[0];
Node head_i = arr[i];
if (head_i == null )
break ;
if (head_0.data >= head_i.data) {
arr[i] = head_i.next;
head_i.next = head_0;
arr[0] = head_i;
}
else {
while (head_0.next != null ) {
if (head_0.next.data
>= head_i.data) {
arr[i] = head_i.next;
head_i.next = head_0.next;
head_0.next = head_i;
break ;
}
head_0 = head_0.next;
if (head_0.next == null ) {
arr[i] = head_i.next;
head_i.next = null ;
head_0.next = head_i;
head_0.next.next = null ;
break ;
}
}
}
}
}
return arr[0];
}
static public void Main()
{
int k = 3;
Node[] arr = new Node[k];
arr[0] = new Node(1);
arr[0].next = new Node(3);
arr[0].next.next = new Node(5);
arr[0].next.next.next = new Node(7);
arr[1] = new Node(2);
arr[1].next = new Node(4);
arr[1].next.next = new Node(6);
arr[1].next.next.next = new Node(8);
arr[2] = new Node(0);
arr[2].next = new Node(9);
arr[2].next.next = new Node(10);
arr[2].next.next.next = new Node(11);
head = mergeKLists(arr, k - 1);
printList(head);
}
}
|
Javascript
<script>
class Node
{
constructor(key)
{
this .data=key;
this .next= null ;
}
}
let head;
let temp;
function printList(node)
{
while (node != null )
{
document.write(node.data + " " );
node = node.next;
}
document.write( "<br>" );
}
function mergeKLists(arr,last)
{
for (let i = 1; i <= last; i++)
{
while ( true )
{
let head_0 = arr[0];
let head_i = arr[i];
if (head_i == null )
break ;
if (head_0.data >= head_i.data)
{
arr[i] = head_i.next;
head_i.next = head_0;
arr[0] = head_i;
}
else
{
while (head_0.next != null )
{
if (head_0.next.data >= head_i.data)
{
arr[i] = head_i.next;
head_i.next = head_0.next;
head_0.next = head_i;
break ;
}
head_0 = head_0.next;
if (head_0.next == null )
{
arr[i] = head_i.next;
head_i.next = null ;
head_0.next = head_i;
head_0.next.next = null ;
break ;
}
}
}
}
}
return arr[0];
}
let k = 3;
let n = 4;
let arr = new Array(k);
arr[0] = new Node(1);
arr[0].next = new Node(3);
arr[0].next.next = new Node(5);
arr[0].next.next.next = new Node(7);
arr[1] = new Node(2);
arr[1].next = new Node(4);
arr[1].next.next = new Node(6);
arr[1].next.next.next = new Node(8);
arr[2] = new Node(0);
arr[2].next = new Node(9);
arr[2].next.next = new Node(10);
arr[2].next.next.next = new Node(11);
head = mergeKLists(arr, k - 1);
printList(head);
</script>
|
Output
0 1 2 3 4 5 6 7 8 9 10 11
Time complexity: O(NK-1), Traversing N times on each of the K lists.
Auxiliary Space: O(1).
Merge K sorted linked lists using Min Heap:
This solution is based on the Min Heap approach. The process must start with creating a MinHeap and inserting the first element of all the K Linked Lists. Remove the root element of Minheap and put it in the output Linked List and insert the next element from the Linked List of the removed element. To get the result the step must continue until there is no element left in the MinHeap.
For a more detailed solution and code checkout, this article Merge k sorted linked lists | Set 2 (Using Min Heap).
Time Complexity: O(N*K*LogK)
Auxiliary Space: O(K)
The idea is to pair up a sorted list after which K/2 list will be left to be merged and repeat this till all the lists gets merged.
Follow the steps below to solve the problem:
- Pair up K lists and merge each pair in linear time using O(N) space.
- After the first cycle, K/2 lists are left each of size 2*N. After the second cycle, K/4 lists are left each of size 4*N and so on.
- Repeat the procedure until we have only one list left.
Below is the implementation of the above idea.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
void printList(Node* node)
{
while (node != NULL) {
printf ( "%d " , node->data);
node = node->next;
}
}
Node* SortedMerge(Node* a, Node* b)
{
Node* result = NULL;
if (a == NULL)
return (b);
else if (b == NULL)
return (a);
if (a->data <= b->data) {
result = a;
result->next = SortedMerge(a->next, b);
}
else {
result = b;
result->next = SortedMerge(a, b->next);
}
return result;
}
Node* mergeKLists(Node* arr[], int last)
{
while (last != 0) {
int i = 0, j = last;
while (i < j) {
arr[i] = SortedMerge(arr[i], arr[j]);
i++, j--;
if (i >= j)
last = j;
}
}
return arr[0];
}
Node* newNode( int data)
{
struct Node* temp = new Node;
temp->data = data;
temp->next = NULL;
return temp;
}
int main()
{
int k = 3;
int n = 4;
Node* arr[k];
arr[0] = newNode(1);
arr[0]->next = newNode(3);
arr[0]->next->next = newNode(5);
arr[0]->next->next->next = newNode(7);
arr[1] = newNode(2);
arr[1]->next = newNode(4);
arr[1]->next->next = newNode(6);
arr[1]->next->next->next = newNode(8);
arr[2] = newNode(0);
arr[2]->next = newNode(9);
arr[2]->next->next = newNode(10);
arr[2]->next->next->next = newNode(11);
Node* head = mergeKLists(arr, k - 1);
printList(head);
return 0;
}
|
Java
public class MergeKSortedLists {
public static Node SortedMerge(Node a, Node b)
{
Node result = null ;
if (a == null )
return b;
else if (b == null )
return a;
if (a.data <= b.data) {
result = a;
result.next = SortedMerge(a.next, b);
}
else {
result = b;
result.next = SortedMerge(a, b.next);
}
return result;
}
public static Node mergeKLists(Node arr[], int last)
{
while (last != 0 ) {
int i = 0 , j = last;
while (i < j) {
arr[i] = SortedMerge(arr[i], arr[j]);
i++;
j--;
if (i >= j)
last = j;
}
}
return arr[ 0 ];
}
public static void printList(Node node)
{
while (node != null ) {
System.out.print(node.data + " " );
node = node.next;
}
}
public static void main(String args[])
{
int k = 3 ;
int n = 4 ;
Node arr[] = new Node[k];
arr[ 0 ] = new Node( 1 );
arr[ 0 ].next = new Node( 3 );
arr[ 0 ].next.next = new Node( 5 );
arr[ 0 ].next.next.next = new Node( 7 );
arr[ 1 ] = new Node( 2 );
arr[ 1 ].next = new Node( 4 );
arr[ 1 ].next.next = new Node( 6 );
arr[ 1 ].next.next.next = new Node( 8 );
arr[ 2 ] = new Node( 0 );
arr[ 2 ].next = new Node( 9 );
arr[ 2 ].next.next = new Node( 10 );
arr[ 2 ].next.next.next = new Node( 11 );
Node head = mergeKLists(arr, k - 1 );
printList(head);
}
}
class Node {
int data;
Node next;
Node( int data) { this .data = data; }
}
|
Python3
class Node:
def __init__( self ):
self .data = 0
self . next = None
def printList(node):
while (node ! = None ):
print (node.data, end = ' ' )
node = node. next
def SortedMerge(a, b):
result = None
if (a = = None ):
return (b)
elif (b = = None ):
return (a)
if (a.data < = b.data):
result = a
result. next = SortedMerge(a. next , b)
else :
result = b
result. next = SortedMerge(a, b. next )
return result
def mergeKLists(arr, last):
while (last ! = 0 ):
i = 0
j = last
while (i < j):
arr[i] = SortedMerge(arr[i], arr[j])
i + = 1
j - = 1
if (i > = j):
last = j
return arr[ 0 ]
def newNode(data):
temp = Node()
temp.data = data
temp. next = None
return temp
if __name__ = = '__main__' :
k = 3
n = 4
arr = [ 0 for i in range (k)]
arr[ 0 ] = newNode( 1 )
arr[ 0 ]. next = newNode( 3 )
arr[ 0 ]. next . next = newNode( 5 )
arr[ 0 ]. next . next . next = newNode( 7 )
arr[ 1 ] = newNode( 2 )
arr[ 1 ]. next = newNode( 4 )
arr[ 1 ]. next . next = newNode( 6 )
arr[ 1 ]. next . next . next = newNode( 8 )
arr[ 2 ] = newNode( 0 )
arr[ 2 ]. next = newNode( 9 )
arr[ 2 ]. next . next = newNode( 10 )
arr[ 2 ]. next . next . next = newNode( 11 )
head = mergeKLists(arr, k - 1 )
printList(head)
|
C#
using System;
public class MergeKSortedLists {
public static Node SortedMerge(Node a, Node b)
{
Node result = null ;
if (a == null )
return b;
else if (b == null )
return a;
if (a.data <= b.data) {
result = a;
result.next = SortedMerge(a.next, b);
}
else {
result = b;
result.next = SortedMerge(a, b.next);
}
return result;
}
public static Node mergeKLists(Node[] arr, int last)
{
while (last != 0) {
int i = 0, j = last;
while (i < j) {
arr[i] = SortedMerge(arr[i], arr[j]);
i++;
j--;
if (i >= j)
last = j;
}
}
return arr[0];
}
public static void printList(Node node)
{
while (node != null ) {
Console.Write(node.data + " " );
node = node.next;
}
}
public static void Main()
{
int k = 3;
Node[] arr = new Node[k];
arr[0] = new Node(1);
arr[0].next = new Node(3);
arr[0].next.next = new Node(5);
arr[0].next.next.next = new Node(7);
arr[1] = new Node(2);
arr[1].next = new Node(4);
arr[1].next.next = new Node(6);
arr[1].next.next.next = new Node(8);
arr[2] = new Node(0);
arr[2].next = new Node(9);
arr[2].next.next = new Node(10);
arr[2].next.next.next = new Node(11);
Node head = mergeKLists(arr, k - 1);
printList(head);
}
}
public class Node {
public int data;
public Node next;
public Node( int data) { this .data = data; }
}
|
Javascript
<script>
class Node {
constructor(val) {
this .data = val;
this .next = null ;
}
}
function SortedMerge(a, b) {
var result = null ;
if (a == null )
return b;
else if (b == null )
return a;
if (a.data <= b.data) {
result = a;
result.next = SortedMerge(a.next, b);
} else {
result = b;
result.next = SortedMerge(a, b.next);
}
return result;
}
function mergeKLists(arr , last) {
while (last != 0) {
var i = 0, j = last;
while (i < j) {
arr[i] = SortedMerge(arr[i], arr[j]);
i++;
j--;
if (i >= j)
last = j;
}
}
return arr[0];
}
function printList(node) {
while (node != null ) {
document.write(node.data + " " );
node = node.next;
}
}
var k = 3;
var n = 4;
var arr = Array(k);
arr[0] = new Node(1);
arr[0].next = new Node(3);
arr[0].next.next = new Node(5);
arr[0].next.next.next = new Node(7);
arr[1] = new Node(2);
arr[1].next = new Node(4);
arr[1].next.next = new Node(6);
arr[1].next.next.next = new Node(8);
arr[2] = new Node(0);
arr[2].next = new Node(9);
arr[2].next.next = new Node(10);
arr[2].next.next.next = new Node(11);
var head = mergeKLists(arr, k - 1);
printList(head);
</script>
|
Output
0 1 2 3 4 5 6 7 8 9 10 11
Time Complexity: O(N * K * log K), As outer while loop in function mergeKLists() runs log K times and every time it processes N*K elements.
Auxiliary Space: O(N * K), Because recursion is used in SortedMerge() and to merge the final 2 linked lists of size N/2, N recursive calls will be made.
Merge K sorted linked lists by Selecting min of top element:
The idea is to select the minimum of top elements iteratively store that in a new node and increment the pointer of the minimum element.
Follow the steps below to solve the problem:
- Find the node with the smallest value in all the K lists and
- Increment the current pointer to the next node of the list where the smallest node is found.
- Now make a new node and append the node to the head node of the resultant list and point the head list with this new node
- Repeat these steps till all nodes have been used.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
Node( int x)
{
data = x;
next = NULL;
}
};
void printList(Node* node)
{
while (node != NULL) {
printf ( "%d " , node->data);
node = node->next;
}
cout << endl;
}
Node* mergeKLists(Node* arr[], int K)
{
Node* head = NULL;
while (1) {
int a = 0;
int z;
Node* curr;
int min = INT_MAX;
for ( int i = 0; i < K; i++) {
if (arr[i] != NULL) {
a++;
if (arr[i]->data < min) {
min = arr[i]->data;
z = i;
}
}
}
if (a != 0) {
arr[z] = arr[z]->next;
Node* temp = new Node(min);
if (head == NULL) {
head = temp;
curr = temp;
}
else {
curr->next = temp;
curr = temp;
}
}
else {
return head;
}
}
}
int main()
{
int k = 3;
int n = 4;
Node* arr[k];
arr[0] = new Node(1);
arr[0]->next = new Node(3);
arr[0]->next->next = new Node(5);
arr[0]->next->next->next = new Node(7);
arr[1] = new Node(2);
arr[1]->next = new Node(4);
arr[1]->next->next = new Node(6);
arr[1]->next->next->next = new Node(8);
arr[2] = new Node(0);
arr[2]->next = new Node(9);
arr[2]->next->next = new Node(10);
arr[2]->next->next->next = new Node(11);
Node* head = mergeKLists(arr, k);
printList(head);
return 0;
}
|
Java
import java.util.*;
class Node {
int data;
Node next;
Node( int x) {
data = x;
next = null ;
}
}
public class MergeKSortedLists {
static void printList(Node node) {
while (node != null ) {
System.out.print(node.data + " " );
node = node.next;
}
System.out.println();
}
static Node mergeKLists(Node[] arr, int K) {
Node head = null ;
Node curr = null ;
while ( true ) {
int a = 0 ;
int z = 0 ;
int min = Integer.MAX_VALUE;
for ( int i = 0 ; i < K; i++) {
if (arr[i] != null ) {
a++;
if (arr[i].data < min) {
min = arr[i].data;
z = i;
}
}
}
if (a != 0 ) {
arr[z] = arr[z].next;
Node temp = new Node(min);
if (head == null ) {
head = temp;
curr = temp;
} else {
curr.next = temp;
curr = temp;
}
} else {
return head;
}
}
}
public static void main(String[] args) {
int k = 3 ;
int n = 4 ;
Node[] arr = new Node[k];
arr[ 0 ] = new Node( 1 );
arr[ 0 ].next = new Node( 3 );
arr[ 0 ].next.next = new Node( 5 );
arr[ 0 ].next.next.next = new Node( 7 );
arr[ 1 ] = new Node( 2 );
arr[ 1 ].next = new Node( 4 );
arr[ 1 ].next.next = new Node( 6 );
arr[ 1 ].next.next.next = new Node( 8 );
arr[ 2 ] = new Node( 0 );
arr[ 2 ].next = new Node( 9 );
arr[ 2 ].next.next = new Node( 10 );
arr[ 2 ].next.next.next = new Node( 11 );
Node head = mergeKLists(arr, k);
printList(head);
}
}
|
Python3
class Node:
def __init__( self , x):
self .data = x
self . next = None
def mergeKLists(arr, K):
from queue import PriorityQueue
pq = PriorityQueue()
for i in range (K):
if arr[i] is not None :
pq.put((arr[i].data, i))
head = Node( None )
curr = head
while not pq.empty():
val, i = pq.get()
curr. next = Node(val)
curr = curr. next
if arr[i]. next is not None :
pq.put((arr[i]. next .data, i))
arr[i] = arr[i]. next
return head. next
def printList(node):
while node is not None :
print (node.data, end = ' ' )
node = node. next
print ()
if __name__ = = '__main__' :
k = 3
n = 4
arr = [ None ] * k
arr[ 0 ] = Node( 1 )
arr[ 0 ]. next = Node( 3 )
arr[ 0 ]. next . next = Node( 5 )
arr[ 0 ]. next . next . next = Node( 7 )
arr[ 1 ] = Node( 2 )
arr[ 1 ]. next = Node( 4 )
arr[ 1 ]. next . next = Node( 6 )
arr[ 1 ]. next . next . next = Node( 8 )
arr[ 2 ] = Node( 0 )
arr[ 2 ]. next = Node( 9 )
arr[ 2 ]. next . next = Node( 10 )
arr[ 2 ]. next . next . next = Node( 11 )
head = mergeKLists(arr, k)
print ( "Merged Linked List:" )
printList(head)
|
C#
using System;
public class Node {
public int data;
public Node next;
public Node( int x)
{
data = x;
next = null ;
}
}
class GFG {
static void PrintList(Node node)
{
while (node != null ) {
Console.Write(node.data + " " );
node = node.next;
}
Console.WriteLine();
}
static Node MergeKLists(Node[] arr, int K)
{
Node head = null ;
Node curr = null ;
while ( true ) {
int a = 0;
int z = 0;
int min = int .MaxValue;
for ( int i = 0; i < K; i++) {
if (arr[i] != null ) {
a++;
if (arr[i].data < min) {
min = arr[i].data;
z = i;
}
}
}
if (a != 0) {
arr[z] = arr[z].next;
Node temp = new Node(min);
if (head == null ) {
head = temp;
curr = temp;
}
else {
curr.next = temp;
curr = temp;
}
}
else {
return head;
}
}
}
public static void Main( string [] args)
{
int k = 3;
Node[] arr = new Node[k];
arr[0] = new Node(1);
arr[0].next = new Node(3);
arr[0].next.next = new Node(5);
arr[0].next.next.next = new Node(7);
arr[1] = new Node(2);
arr[1].next = new Node(4);
arr[1].next.next = new Node(6);
arr[1].next.next.next = new Node(8);
arr[2] = new Node(0);
arr[2].next = new Node(9);
arr[2].next.next = new Node(10);
arr[2].next.next.next = new Node(11);
Node head = MergeKLists(arr, k);
PrintList(head);
}
}
|
Javascript
class ListNode {
constructor(val) {
this .val = val;
this .next = null ;
}
}
const mergeKLists = (lists) => {
const mergeTwoLists = (l1, l2) => {
if (!l1) return l2;
if (!l2) return l1;
if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
};
const mergeKListsRecursively = (lists, start, end) => {
if (start === end) {
return lists[start];
}
const mid = Math.floor((start + end) / 2);
const left = mergeKListsRecursively(lists, start, mid);
const right = mergeKListsRecursively(lists, mid + 1, end);
return mergeTwoLists(left, right);
};
if (lists.length === 0) return null ;
return mergeKListsRecursively(lists, 0, lists.length - 1);
};
const k = 3;
const arr = [];
arr[0] = new ListNode(1);
arr[0].next = new ListNode(3);
arr[0].next.next = new ListNode(5);
arr[0].next.next.next = new ListNode(7);
arr[1] = new ListNode(2);
arr[1].next = new ListNode(4);
arr[1].next.next = new ListNode(6);
arr[1].next.next.next = new ListNode(8);
arr[2] = new ListNode(0);
arr[2].next = new ListNode(9);
arr[2].next.next = new ListNode(10);
arr[2].next.next.next = new ListNode(11);
const head = mergeKLists(arr);
const printList = (node) => {
while (node !== null ) {
process.stdout.write(`${node.val} `);
node = node.next;
}
console.log();
};
printList(head);
|
Output
0 1 2 3 4 5 6 7 8 9 10 11
Time complexity: O(N*K2), There are N*K nodes in total and to find the smallest node it takes K times so for the N*K nodes it will take N*K*K time.
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
30 Oct, 2023
Like Article
Save Article