Last Updated: 28 Dec, 2020

Merge k sorted lists

Hard
Asked in companies
AmazonIntuitPayPal

Problem statement

Given 'k' sorted linked lists, each list is sorted in increasing order. You need to merge all these lists into one single sorted list. You need to return the head of the final linked list.


For example:
Input:
3
3
4 6 8
3
2 5 7 
2
1 9

Output:
1 2 4 5 6 7 8 9 

Explanation:
First list is: 4 -> 6 -> 8 -> NULL
Second list is: 2 -> 5 -> 7 -> NULL
Third list is: 1 -> 9 -> NULL
The final list would be: 1 -> 2 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> NULL
Input format:
The first line consists of an integer 'k' denoting the number of lists.

Next 2*k lines consists of 'n', the size of linked list and the 'n' space-separated elements on the new line.
Output format:.
The output consists of space-separated elements of the merged sorted list.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.

Approaches

01 Approach

Here we will perform a brute force of adding all the nodes in a separate list and then sort it.

  1. Traverse through all the linked lists and add each node in a different array.
  2. Sort the array.
  3. Make a new linked list and add all of the elements of the sorted array.

02 Approach

  1. The idea is to use priority queue to reduce searching time for list with smaller head value.
  2. We will maintain a priority queue for the head node of K list.
  3. The top of the queue gives the nodes with smaller value.
  4. We will add this head node into our final list and move the head pointer of that list to the next node of that list and update it in our queue.
  5. We will repeat step 3 and 4, until the queue becomes empty.