The idea is to initialize the result as empty. Now one by one merge every linked list into the resultant list using the idea of merging two sorted linked lists. We always consider the result as first list and other list as second. At the end, we return result.
Time complexity: O(n*k*k), For simplicity, let us assume that every list is of equal size n. In the worst case. we take n + 2n + 3n ..... + k * n time. The sum of this series is n * k * (k + 1) / 2 which is O(n * k * k). Auxiliary Space: O(1).
[Naive Approach - 2] - By repeatedly selecting the minimum node
The idea is to iterate through all the k head nodes and append the head node with minimum value to the resultant list. Increment the head to next node. Repeat this process until all nodes are processed.
Step by step approach:
Initialize a dummy head for the resultant list.
Find the node with the smallest value in all the k lists.
Increment the current pointer to the next node of the list where the smallest node is found.
Append the node with smallest value to the resultant list.
Time complexity: O(n * k2), There are n*k nodes in total (assuming every list has O(n) nodes) 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(1)
[Expected Approach - 1] -Using Min Heap (Works better for unequal sized lists)
This solution is mainly an optimization over the previous approach. Instead of linearly traversing the array to find the minimum, we use min heap data structure and reduce the time complexity of this operation to O(Log k).
Time Complexity: O(n * k * log k) if we have k lists of size O(n) each. We can also say O(n * Log k) where n is the total number of nodes. Auxiliary Space: O(k)
[ExpectedApproach- 2]-Using DivideandConquer(Works better for equal sized lists)
The idea is to use divide and conquer by recursively splitting the k lists into two halves until we have pairs of lists to merge, then merge these pairs using a two-way merge procedure (similar to merge sort's merge step), and continue this process back up through the recursion tree until all lists are merged into a single sorted list.
Step by step approach:
Split k lists into two parts: lists[0...mid] and lists[mid+1...end].
Recursively merge the left half of lists to get first sorted list.
Recursively merge the right half of lists to get second sorted list.
Merge the above two sorted lists using two-pointer approach.