Merge k Sorted Arrays | Practice | GeeksforGeeks

Given K sorted arrays arranged in the form of a matrix of size K*K. The task is to merge them into one sorted array.
Example 1: 
Input:
K = 3
arr[][] = {{1,2,3},{4,5,6},{7,8,9}}
Output: 1 2 3 4 5 6 7 8 9
Explanation:Above test case has 3 sorted
arrays of size 3, 3, 3
arr[][] = [[1, 2, 3],[4, 5, 6], 
[7, 8, 9]]
The merged list will be 
[1, 2, 3, 4, 5, 6, 7, 8, 9].
Example 2: 
Input:
K = 4
arr[][]={{1,2,3,4}{2,2,3,4},
         {5,5,6,6},{7,8,9,9}}
Output:
1 2 2 2 3 3 4 4 5 5 6 6 7 8 9 9 
Explanation: Above test case has 4 sorted
arrays of size 4, 4, 4, 4
arr[][] = [[1, 2, 2, 2], [3, 3, 4, 4],
[5, 5, 6, 6]  [7, 8, 9, 9 ]]
The merged list will be 
[1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 
6, 6, 7, 8, 9, 9 ].
Your Task:
You do not need to read input or print anything. Your task is to complete mergeKArrays() function which takes 2 arguments, an arr[K][K] 2D Matrix containing K sorted arrays and an integer K denoting the number of sorted arrays, as input and returns the merged sorted array ( as a pointer to the merged sorted arrays in cpp, as an ArrayList in java, and list in python)
Expected Time Complexity: O(K2*Log(K))
Expected Auxiliary Space: O(K)
Constraints:
1 <= K <= 100
0
shreyash9779665 days ago
SIMPLEST SOLUTION EVER!!
 vector<int> mergeKArrays(vector<vector<int>> a, int n)
    {
        //code here
        vector<int>v;
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                v.push_back(a[i][j]);
            }
        }
        sort(v.begin(),v.end());
        return v;
    }
 
 
0
velspace015 days ago
Java trivial sol TC-->O(K^2) SC-->O(K)
 ArrayList<Integer> ans=new ArrayList<>();
        for(int i=0;i<k;i++){
            for(int j=0;j<k;j++){
                ans.add(arr[i][j]);
            }
        }
        Collections.sort(ans);
        return ans;
0
shandlikamal2481 week ago
O(KLOGK) java soln.
static class Pair   {       int n;       int row;       int col;       Pair(int i,int j,int k)       {           n=i;           row=j;           col=k;       }   }   public static ArrayList<Integer> mergeKArrays(int[][] arr,int K)    {       // Write your code here.       ArrayList<Integer> array=new ArrayList<>();       PriorityQueue<Pair> pq=new PriorityQueue<>(new Comparator<Pair>()       {           public int compare(Pair a,Pair b)           {               return Integer.compare(a.n,b.n);           }       });       for(int i=0;i<K;i++)       {           pq.add(new Pair(arr[i][0],i,0));       }              while(!pq.isEmpty())       {           Pair next=pq.poll();                      array.add(next.n);           int row=next.row;           int col=next.col;           if(col+1<K)           pq.add(new Pair(arr[row][col+1],row,col+1));                                        }       return array;
 
0
baviral1 week ago
class Solution
{
    public:
    
    class node{
        public:
        int data;
        int i;
        int j;
        
        node(int data, int row, int col){
            this->data = data;
            this->i = row;
            this->j = col;
        }
    };
    
    class compare{
        public:
        bool operator()(node* a, node* b){
            return a->data > b->data;
        }
    };
    
    vector<int> mergeKArrays(vector<vector<int>> arr, int K)
    {
        priority_queue<node*, vector<node*>, compare> pq;
        vector<int> ans;
        
        for(int i=0; i<K; i++){
            node* temp = new node(arr[i][0],i,0);
            pq.push(temp);
        }
        
        while(!pq.empty()){
            node* temp = pq.top();
            ans.push_back(temp->data);
            pq.pop();
            
            int i = temp->i;
            int j = temp->j;
            
            if(j+1 < arr[i].size())
            {
                node* next = new node(arr[i][j+1], i, j+1);
                pq.push(next);
            }
        }
        return ans;
    }
};
0
mayank_nigam2 weeks ago
 Java Solution - 
public static class pair implements Comparable<pair>{              int li;       int di;       int val;              public pair(int li,int di,int val){                      this.li=li;           this.di=di;           this.val=val;       }              public int compareTo(pair o){           return this.val-o.val;       }
   }   public static ArrayList<Integer> mergeKArrays(int[][] arr,int K)    {     ArrayList<Integer> res= new ArrayList<>();          PriorityQueue<pair> pq= new PriorityQueue<>();               for(int i=0;i<arr.length;i++){            pair p = new pair(i,0,arr[i][0]);      pq.add(p);     }               while(pq.size()>0){                  pair p = pq.remove();         res.add(p.val);                  p.di++;  // di - data index , li - list index , val - value                   if(p.di<arr[p.li].length){             p.val=arr[p.li][p.di];             pq.add(p);         }     }         return res;        }
-3
rishabh21cse2 weeks ago
MOST EASY C++ SOLUTION.....
 vector<int> v;              for(int i=0;i<K;i++){           for(int j=0;j<K;j++)           v.push_back(arr[i][j]);       }       sort(v.begin(),v.end());       return v;       
0
amarrajsmart1972 weeks ago
C++ Solution...
vector<int> mergeKArrays(vector<vector<int>> arr, int K)   {       //code here       vector<int> v;       for(int i=0;i<K;i++)       {           for(int j=0;j<K;j++)           {               v.push_back(arr[i][j]);           }       }       sort(v.begin(),v.end());       return v;          }
0
bhaskarmaheshwari82 weeks ago
vector<int> merge(vector<int>&a,vector<int> &b)   {       int n1=a.size();       int n2=b.size();       vector<int> v(n1+n2);       int i=0,j=0,k=0;       while(i<n1&&j<n2)       {           if(a[i]<=b[j])           {               v[k++]=a[i++];           }           else           {               v[k++]=b[j++];           }       }       while(i<n1)       {           v[k++]=a[i++];       }              while(j<n2)       {           v[k++]=b[j++];       }              return v;          }   vector<int> mergeKArrays(vector<vector<int>> arr, int k)   {       //code here       vector<int> ans=arr[0];       for(int i=1;i<k;i++)       {           ans=merge(ans,arr[i]);       }       return ans;   }
0
mohitraj27412 weeks ago
time- 0.56 seconds
complexity- O(K^2)
 
class Solution{   public:   //write a func to merge 2 sorted arrays first   vector<int> merge(vector<int>a,vector<int>b,int m,int n)   {   vector<int>ans;       int i=0;       int j=0;       while(i<m && j<n)       {           if(a[i]<=b[j])           {ans.push_back(a[i]);i++;}           else           {ans.push_back(b[j]);j++;}                  }       while(i<m)       {ans.push_back(a[i]);i++;       }       while(j<n)       {ans.push_back(b[j]);j++;       }              return ans;   }   // apply the above function in final function   vector<int> mergeKArrays(vector<vector<int>> arr, int K)   {       //code here       if(K==1)       return arr[0];              vector<int> res;       res= merge(arr[0],arr[1],K,K);
      for(int i=2;i<=K-1;i++)       {           res= merge(res,arr[i],K*i,K);      }       return res;   }};
0
akashmarkad22102 weeks ago
JAVA Solution
 
 public static ArrayList<Integer> mergeKArrays(int[][] arr,int K)    {       // Write your code here.              ArrayList<Integer> ans = new ArrayList<>();              for (int i = 0 ; i < K ; i++)       {           for(int j = 0 ; j < K ; j++)           {               ans.add(arr[i][j]);           }       }              Collections.sort(ans);              return ans;   }
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.