Kth element in Matrix | Practice | GeeksforGeeks

Given a N x N matrix, where every row and column is sorted in non-decreasing order. Find the kth smallest element in the matrix.
Input:
N = 4
mat[][] =     {{16, 28, 60, 64},
                   {22, 41, 63, 91},
                   {27, 50, 87, 93},
                   {36, 78, 87, 94 }}
K = 3
Output: 27
Explanation: 27 is the 3rd smallest element.
 
Input:
N = 4
mat[][] =     {{10, 20, 30, 40}
                   {15, 25, 35, 45}
                   {24, 29, 37, 48}
                   {32, 33, 39, 50}}
K = 7
Output: 30
Explanation: 30 is the 7th smallest element.
 
Expected Time Complexity: O(K*Log(N))
Expected Auxiliary Space: O(N)
 
Constraints:
1 <= N <= 50
1 <= mat[][] <= 10000
1 <= K <= N*N

 
0
pratapshivendrasingh171 day ago
Optimal Solution
int kthSmallest(int mat[MAX][MAX], int n, int k)
{
  //Your code 
  
   int start = mat[0][0];
   int end = mat[n-1][n-1];
   
   while(start < end)
   {
       int mid = start+(end-start)/2;
       
       int count = 0;
       for(int i = 0; i < n; i++)
       {
           int upperbound = upper_bound(mat[i],mat[i]+n,mid) - mat[i];
           count += upperbound;
       }
       
       if(count<k)
       {
           start=mid+1;
       }
       else
       {
           end=mid;
       }
   }
   
   return start;
}

0
mayankkannojia293 days ago
java-.80./1.83(Best Solution using heap)
class list{   int i;   int j;   list(int i ,int j){       this.i=i;       this.j=j;   }  }class sort implements Comparator<list>{   public int compare(list a, list b){       int[][] mat = Solution.matrix();       return mat[a.i][a.j]-mat[b.i][b.j];   }}class Solution{   static int[][] b;   public static int[][] matrix(){       return b;   }public static int kthSmallest(int[][]mat,int N,int k){    if(k==1) return mat[0][0];      b = mat;      PriorityQueue<list> pq = new PriorityQueue<>(new sort());      pq.add(new list(1,0));       pq.add(new list(0,1));    for(int i =2;i<k;i++){        list l = pq.poll();        if(l.j+1<N) pq.add(new list(l.i,l.j+1));        if(l.j==0 && l.i+1<N) pq.add(new list(l.i+1,0));   }   list l = pq.poll();   return mat[l.i][l.j];}}
0
ayushmahobia015 days ago
int m = n*n;int temp[m]={0};int l=0;for(int i=0;i<n;i++)   {              for(int j=0;j<n;j++)       {        temp[l++]= mat[i][j];       }   }   sort(temp,temp+m);   return temp[k-1];
0
giridharsonu1231 week ago
JavaScript Solution
let result = []   for (let i = 0; i < mat.length; i++) {       for (let j = 0; j < mat.length; j++) {           result.push(mat[i][j])       }   }   let sort_result = result.sort((a,b) => a - b)   return sort_result[k - 1]
-4
hharshit81182 weeks ago
int kthSmallest(int arr[MAX][MAX], int n, int k){   priority_queue<int> pq;   for(int i = 0; i< n; i++){       for(int j = 0; j< n; j++){           if(k!=0){               pq.push(arr[i][j]);               k--;           }           else if(pq.top() > arr[i][j]){               pq.pop();               pq.push(arr[i][j]);           }       }   }   return pq.top();} 
+1
gulashanshashishekhar292 weeks ago
// Time Complexity: O(k*log(n))
// Space Complexity: O(n)

//define min heap
priority_queue <pair<int, pair<int, int>>, 
                vector<pair<int, pair<int, int>>>,   
                greater<pair<int, pair<int, int>>>
                > pq;
// To avoid repetition
// Initialise min heap with first row
for (int i = 0; i < n; i++) pq.push({mat[0][i], {0, i}});
// pop min elements from heap k-1 times and while doing so
// insert the element below the min element to the heap
for (int i = 0; i < k-1; i++) {
    int p = pq.top().second.first,  // row 
        q = pq.top().second.second; // column
        
    pq.pop();
    if (p+1 < n) pq.push({mat[p+1][q], {p+1, q}});
}
return pq.top().first; // return kth element
0
gcharansaicis192 weeks ago
int kthSmallest(int mat[MAX][MAX], int n, int k){      priority_queue<int> pq;   int count=0;   for(int i=0;i<n;i++)   {       for(int j=0;j<n;j++)       {           if(count>k)           {               if(pq.top()<mat[i][j])               {                   break;               }               else               {                    pq.push(mat[i][j]);                    count++;               }           }           else           {               pq.push(mat[i][j]);               count++;           }       }   }   for(int j=0;j<count-k;j++)   {   //   cout<<pq.top()<<" ";      pq.pop();   }   return pq.top();
}
0
revolverocelot2 weeks ago
Although it is given in the problem statement that the matrix is row-wise and column-wise sorted. Yet most of the answers here use one of these properties. 
Can anyone provide a solution where both of these properties are utilized to reach an optimal solution?
0
prashant6013 weeks ago
A simple approach using multiset.
 
int kthSmallest(int mat[MAX][MAX], int n, int k)
{
   multiset<int> s;
   
   for(int i=0;i<n;i++){
       for(int j=0;j<n;j++){
           s.insert(mat[i][j]);
           if(s.size()>k){
               s.erase(--s.end()); //at max, k element will be there in set
           }
       }
   }
       auto it= s.begin();
       
       for(int i=0;i<k-1;i++) it++;
       return *it; 
   }
0
satyamrau97213 weeks ago
public static int kthSmallest(int[][]mat,int n,int k){   //By techy Satyam     int temp[] = new int[n * n];       int l = 0;           // copy the elements of matrix       // one by one into temp[]       for (int i = 0; i < n; i++)           for (int j = 0; j < n; j++)               temp[l++] = mat[i][j];           // sort temp[]       Arrays.sort(temp);               // copy the elements of temp[]       // one by one in mat[][]      
     // return the desired element          return temp[k-1];                              }
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.