Merge K sorted linked lists | Practice | GeeksforGeeks

Given K sorted linked lists of different sizes. The task is to merge them in such a way that after merging they will be a single sorted linked list. 
Example 1:
Input:
K = 4
value = {{1,2,3},{4 5},{5 6},{7,8}}
Output: 1 2 3 4 5 5 6 7 8
Explanation:
The test case has 4 sorted linked 
list of size 3, 2, 2, 2
1st    list     1 -> 2-> 3
2nd   list      4->5
3rd    list      5->6
4th    list      7->8
The merged list will be
1->2->3->4->5->5->6->7->8.

Example 2:
Input:
K = 3
value = {{1,3},{4,5,6},{8}}
Output: 1 3 4 5 6 8
Explanation:
The test case has 3 sorted linked
list of size 2, 3, 1.
1st list 1 -> 3
2nd list 4 -> 5 -> 6
3rd list 8
The merged list will be
1->3->4->5->6->8.

Your Task:
The task is to complete the function mergeKList() which merges the K given lists into a sorted one. The printing is done automatically by the driver code.
Expected Time Complexity: O(nk Logk)
Expected Auxiliary Space: O(k)
Note: n is the maximum size of all the k link list
Constraints
1 <= K <= 103
 
0
somain1005in 11 hours
JAVA  3.74/5.7
 
 Node mergeKList(Node[]arr,int K)   {       //Add your code here.       if(arr.length==1)       return arr[0];       Node x=arr[0];       Node y=arr[0];       int count=0;              for(int i=0;i<K-1;i++)       {           int j=0;           x=arr[i];           y=arr[i];                      while(y!=null)           {               count++;               y=y.next;           }           while(x.next!=null)           x=x.next;
           x.next=arr[i+1];       }              y=arr[K-1];       while(y!=null)           {               count++;               y=y.next;           }                Node head=arr[0];     Node curr=head;     int j=0;     int[] array=new int[count];          while(curr!=null)     {         array[j++]=curr.data;         curr=curr.next;     }          Arrays.sort(array);     curr=head;     int s=0;          while(curr!=null)     {         curr.data=array[s++];         curr=curr.next;     }          return head;   }
+1
shahabuddinbravo40in 7 hours
class Solution{ public:    //Function to merge K sorted linked list.   Node * mergeKLists(Node *arr[], int K)   {       //   vector<int>v;                //   for(int i=0;i<K;i++){       //       while(arr[i]!=NULL)       //       {       //           v.push_back(arr[i]->data);       //           arr[i]=arr[i]->next;       //       }       //   }                //   sort(v.begin(),v.end());                //   Node *list=new Node(-1),*head=list;       //   for(int i=0;i<v.size();i++){       //       Node *new_node=new Node(v[i]);       //       list->next=new_node;       //       list=list->next;       //   }                //   head=head->next;                //   return head;                     priority_queue< pair<int,Node*>,vector<pair<int,Node*>>,greater<pair<int,Node*>> >minH;              for(int i=0;i<K;i++)       {           minH.push({arr[i]->data,arr[i]});       }              Node *list=new Node(-1),*head=list;       while(!minH.empty())       {           pair<int,Node*> p=minH.top();                      Node *new_node=new Node(p.first);           list->next=new_node;           list=list->next;                      minH.pop();                      if(p.second->next!=NULL){             p.second=p.second->next;             minH.push({p.second->data,p.second});           }       }              head=head->next;              return head;   }}; 
0
sidharthsitesh2in 4 minutes
Easy Python Solution
 
 array=[]       for i in arr:           while i:               array.append(i.data)               i=i.next              array.sort()              head=Node(None)       curr=head       for i in array:           curr.next=Node(i)           curr=curr.next       return head.next
0
abhijeet1940322 hours ago
The idea behind this approach is two first merge 2 linked lists and then keep on adding other remaining linked lists to make it one big linked list.
 
Code in C++
 
// Function to merge 2 linked lists   Node *merge(Node *a,Node *b)   {       if(a==NULL)       return b;       if(b==NULL)       return a;       Node *head ;       Node *tail ;       if(a->data<=b->data)       {           head = tail = a;           a = a->next;       }       else       {           head = tail = b;           b = b->next;       }       while(a!=NULL && b!=NULL)       {           if(a->data<=b->data)           {               tail->next = a;               tail = tail->next;               a = a->next;           }           else           {               tail ->next = b;               tail = tail->next;               b = b->next;           }       }       if(a!=NULL)       tail->next = a;       else       tail->next = b;       return head;   }   //Function to merge K sorted linked list.   Node * mergeKLists(Node *arr[], int k)   {          Node *first = arr[0];          for(int i=1;i<k;i++)          {              Node *second = arr[i];              first = merge(first,second);          }          return first;   }
0
santoshkumar15novmth4 days ago
class compare{   public:     bool operator() (Node* a, Node* b) {         return a->data > b->data;     }};class Solution{ public:   //Function to merge K sorted linked list.   Node * mergeKLists(Node *lists[], int k)   {       priority_queue<Node*,vector<Node*> ,compare> q;       Node* dummy = new Node(-1);       Node* tail = dummy;       for(int i=0; i<k; i++)       {           if(lists[i]!=NULL)           {               q.push(lists[i]);           }       }       while(q.size())       {           Node* temp=q.top();           tail->next = temp;           tail = temp;           q.pop();           if(temp->next!=NULL)               q.push(temp->next);       }       return dummy->next;   }};
0
shreyassakariya20021 week ago
//Time : O(nk Logk)
//Space: O(k)

Node * mergeKLists(Node *arr[], int k)
    {
        priority_queue<pair<int,Node*>,vector<pair<int,Node*>>,greater<pair<int,Node*>>> pq;
        
        for(int i=0;i<k;i++)
            pq.push({arr[i]->data , arr[i]});
        
        Node *ans=new Node(-1);
        Node *curr = ans;
        
        while(!pq.empty())
        {
            Node *temp=pq.top().second;
            pq.pop();
            
            curr->next = new Node(temp->data);
            curr=curr->next;
            
            temp=temp->next;
            if(temp)
                pq.push({temp->data,temp});
        }
        return ans->next;
    }
0
rishu
This comment was deleted.
0
rishu1 week ago
class Solution
{
   //Function to merge K sorted linked list.
   Node mergeKList(Node[]arr,int K)
   {
       //Add your code here.
       int i=0;
       if(arr.length==1){
           return arr[0];
       }
       Node head = merge(arr[0],arr[1],i+1,arr,K);
       return head;
        
   }
   static Node merge(Node a, Node b, int i, Node[]arr,int K){
       Node temp1 = a;
       Node temp2 = b;
       if(i<K-1){
           Node X = merge(arr[i], arr[i+1], i+1,arr, K );
           temp2=X;
       }
       Node dummy = new Node(-1);
       Node tail=dummy;
       while(temp1!=null && temp2!=null){
           if(temp1.data<=temp2.data){
               tail.next=temp1;
               tail=tail.next;
               temp1=temp1.next;
           }
           else{
               tail.next=temp2;
               tail=tail.next;
               temp2=temp2.next;
           } 
               
       }
       if(temp1!=null){
           tail.next=temp1;
       }
       if(temp2!=null){
           tail.next=temp2;
       }
       return dummy.next;
   }
}
0
rishu
This comment was deleted.
0
amarrajsmart1972 weeks ago
Node * mergeKLists(Node *arr[], int K)   {          // Your code here          vector<int> v;          int i=0;          int count=1;          while(count<=K)          {              if(!arr[i])              {                  count++;                  i++;              }              else              {                  v.push_back(arr[i]->data);                  arr[i]=arr[i]->next;              }          }          sort(v.begin(),v.end());          Node*head=new Node(-1);          Node* it=head;          i=0;          while(i<v.size())          {              it->next=new Node(v[i++]);              it=it->next;          }           head=head->next;          return head;             }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.