# Merge K sorted linked lists | Set 1

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.

Recommended Practice

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:

## Javascript



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)

## Merge K sorted linked lists usingDivide and Conquer:

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++

 // C++ program to merge k sorted // arrays of size n each #include using namespace std;   // A Linked List node struct Node {     int data;     Node* next; };   /* Function to print nodes in    a given linked list */ void printList(Node* node) {     while (node != NULL) {         printf("%d ", node->data);         node = node->next;     } }   /* Takes two lists sorted in increasing order, and merge    their nodes together to make one big sorted list. Below    function takes O(n) extra space for recursive calls,     */ Node* SortedMerge(Node* a, Node* b) {     Node* result = NULL;       /* Base cases */     if (a == NULL)         return (b);     else if (b == NULL)         return (a);       /* Pick either a or b, and recur */     if (a->data <= b->data) {         result = a;         result->next = SortedMerge(a->next, b);     }     else {         result = b;         result->next = SortedMerge(a, b->next);     }       return result; }   // The main function that takes an array of lists // arr[0..last] and generates the sorted output Node* mergeKLists(Node* arr[], int last) {     // repeat until only one list is left     while (last != 0) {         int i = 0, j = last;           // (i, j) forms a pair         while (i < j) {             // merge List i with List j and store             // merged list in List i             arr[i] = SortedMerge(arr[i], arr[j]);               // consider next pair             i++, j--;               // If all pairs are merged, update last             if (i >= j)                 last = j;         }     }       return arr[0]; }   // Utility function to create a new node. Node* newNode(int data) {     struct Node* temp = new Node;     temp->data = data;     temp->next = NULL;     return temp; }   // Driver program to test above functions int main() {     int k = 3; // Number of linked lists     int n = 4; // Number of elements in each list       // an array of pointers storing the head nodes     // of the linked lists     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);       // Merge all lists     Node* head = mergeKLists(arr, k - 1);       printList(head);       return 0; }

## Java

 // Java program to merge k sorted arrays of size n each public class MergeKSortedLists {       /* Takes two lists sorted in increasing order, and merge     their nodes together to make one big sorted list. Below     function takes O(Log n) extra space for recursive calls,     but it can be easily modified to work with same time and     O(1) extra space  */     public static Node SortedMerge(Node a, Node b)     {         Node result = null;         /* Base cases */         if (a == null)             return b;         else if (b == null)             return a;           /* Pick either a or b, and recur */         if (a.data <= b.data) {             result = a;             result.next = SortedMerge(a.next, b);         }         else {             result = b;             result.next = SortedMerge(a, b.next);         }           return result;     }       // The main function that takes an array of lists     // arr[0..last] and generates the sorted output     public static Node mergeKLists(Node arr[], int last)     {         // repeat until only one list is left         while (last != 0) {             int i = 0, j = last;               // (i, j) forms a pair             while (i < j) {                 // merge List i with List j and store                 // merged list in List i                 arr[i] = SortedMerge(arr[i], arr[j]);                   // consider next pair                 i++;                 j--;                   // If all pairs are merged, update last                 if (i >= j)                     last = j;             }         }           return arr[0];     }       /* Function to print nodes in a given linked list */     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; // Number of linked lists         int n = 4; // Number of elements in each list           // an array of pointers storing the head nodes         // of the linked lists         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);           // Merge all lists         Node head = mergeKLists(arr, k - 1);         printList(head);     } }   class Node {     int data;     Node next;     Node(int data) { this.data = data; } } // This code is contributed by Gaurav Tiwari

## Python3

 # Python3 program to merge k sorted # arrays of size n each   # A Linked List node class Node:       def __init__(self):           self.data = 0         self.next = None   # Function to print nodes in a # given linked list def printList(node):       while (node != None):         print(node.data, end=' ')         node = node.next   # Takes two lists sorted in increasing order, # and merge their nodes together to make one # big sorted list. Below function takes # O(Log n) extra space for recursive calls, # but it can be easily modified to work with # same time and O(1) extra space def SortedMerge(a, b):       result = None       # Base cases     if (a == None):         return(b)     elif (b == None):         return(a)       # Pick either a or b, and recur     if (a.data <= b.data):         result = a         result.next = SortedMerge(a.next, b)     else:         result = b         result.next = SortedMerge(a, b.next)       return result   # The main function that takes an array of lists # arr[0..last] and generates the sorted output def mergeKLists(arr, last):       # Repeat until only one list is left     while (last != 0):         i = 0         j = last           # (i, j) forms a pair         while (i < j):               # Merge List i with List j and store             # merged list in List i             arr[i] = SortedMerge(arr[i], arr[j])               # Consider next pair             i += 1             j -= 1               # If all pairs are merged, update last             if (i >= j):                 last = j       return arr[0]   # Utility function to create a new node. def newNode(data):       temp = Node()     temp.data = data     temp.next = None     return temp     # Driver code if __name__ == '__main__':       # Number of linked lists     k = 3       # Number of elements in each list     n = 4       # An array of pointers storing the     # head nodes of the linked lists     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)       # Merge all lists     head = mergeKLists(arr, k - 1)       printList(head)   # This code is contributed by rutvik_56

## C#

 // C# program to merge k sorted arrays of size n each using System;   public class MergeKSortedLists {       /* Takes two lists sorted in     increasing order, and merge     their nodes together to make     one big sorted list. Below     function takes O(Log n) extra     space for recursive calls,     but it can be easily modified     to work with same time and     O(1) extra space */     public static Node SortedMerge(Node a, Node b)     {         Node result = null;           /* Base cases */         if (a == null)             return b;         else if (b == null)             return a;           /* Pick either a or b, and recur */         if (a.data <= b.data) {             result = a;             result.next = SortedMerge(a.next, b);         }         else {             result = b;             result.next = SortedMerge(a, b.next);         }           return result;     }       // The main function that takes     // an array of lists arr[0..last]     // and generates the sorted output     public static Node mergeKLists(Node[] arr, int last)     {         // repeat until only one list is left         while (last != 0) {             int i = 0, j = last;               // (i, j) forms a pair             while (i < j) {                 // merge List i with List j and store                 // merged list in List i                 arr[i] = SortedMerge(arr[i], arr[j]);                   // consider next pair                 i++;                 j--;                   // If all pairs are merged, update last                 if (i >= j)                     last = j;             }         }           return arr[0];     }       /* Function to print nodes in a given linked list */     public static void printList(Node node)     {         while (node != null) {             Console.Write(node.data + " ");             node = node.next;         }     }       public static void Main()     {         int k = 3; // Number of linked lists         // int n = 4; // Number of elements in each list           // An array of pointers storing the head nodes         // of the linked lists         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);           // Merge all lists         Node head = mergeKLists(arr, k - 1);         printList(head);     } }   public class Node {     public int data;     public Node next;     public Node(int data) { this.data = data; } }   /* This code contributed by PrinciRaj1992 */

## Javascript



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:

## Javascript

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!

Previous
Next