Given K sorted linked lists of size N each, merge them and print the sorted output.
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
Method 1 (Simple)
A Simple Solution is to initialize result as first list. Now traverse all lists starting from second list. Insert every node of currently traversed list into result in a sorted way. Time complexity of this solution is O(N2) where N is total number of nodes, i.e., N = kn.
Method 2 (Using Min Heap)
A Better solution is to use Min Heap based solution which is discussed here for arrays. Time complexity of this solution would be O(nk Log k)
Method 3 (Using Divide and Conquer))
In this post, Divide and Conquer approach is discussed. This approach doesn’t require extra space for heap and works in O(nk Log k)
We already know that merging of two linked lists can be done in O(n) time and O(1) space (For arrays O(n) space is required). The idea is to pair up K lists and merge each pair in linear time using O(1) space. After first cycle, K/2 lists are left each of size 2*N. After second cycle, K/4 lists are left each of size 4*N and so on. We repeat the procedure until we have only one list left.
Below is implementation of the above idea.
0 1 2 3 4 5 6 7 8 9 10 11
Time Complexity of above algorithm is O(nk logk) as outer while loop in function mergeKLists() runs log k times and every time we are processing nk elements.
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Sorted merge of two sorted doubly circular linked lists
- Merge two sorted linked lists
- Merge k sorted linked lists | Set 2 (Using Min Heap)
- Merge two sorted linked lists such that merged list is in reverse order
- Merge K sorted Doubly Linked List in Sorted Order
- Merge two sorted lists (in-place)
- Merge Sort for Linked Lists
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Difference of two Linked Lists using Merge sort
- Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
- In-place Merge two linked lists without changing links of first list
- Merge two sorted linked list without duplicates
- Intersection of two Sorted Linked Lists
- Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?