Median in a row-wise sorted Matrix | Practice | GeeksforGeeks

Given a row wise sorted matrix of size RxC where R and C are always odd, find the median of the matrix.
Example 1:
Input:
R = 3, C = 3
M = [[1, 3, 5], 
     [2, 6, 9], 
     [3, 6, 9]]

Output: 5

Explanation:
Sorting matrix elements gives us 
{1,2,3,3,5,6,6,9,9}. Hence, 5 is median. 

 
Example 2:
Input:
R = 3, C = 1
M = [[1], [2], [3]]
Output: 2


Your Task:  
You don't need to read input or print anything. Your task is to complete the function median() which takes the integers R and C along with the 2D matrix as input parameters and returns the median of the matrix.

Expected Time Complexity: O(32 * R * log(C))
Expected Auxiliary Space: O(1)

Constraints:
1<= R,C <=150
1<= matrix[i][j] <=2000

 
0
ashu0120024 days ago
vector<int> v;       int s=r*c;       for(int i=0;i<r;i++){           for(int j=0;j<c;j++){               v.push_back(m[i][j]);           }       }       sort(v.begin(),v.end());       return v[(s/2)];
+1
kshitij14101 week ago
int median(vector<vector<int>> &matrix, int r, int c){              int ans=-1;       int high=2000;       int low=1;       int medianplace=((r*c)/2)+1 ;                     while(low<=high)       {           int mid=(low+high)/2;                      int count=0;                      for(int i=0;i<r;i++)           {               count+=upper_bound(matrix[i].begin(),matrix[i].end(),mid) -matrix[i].begin();           }                      if(count>=medianplace)           {               ans=mid;               high=mid-1;           }           else           low=mid+1;                  }              return ans;   }
0
anishmeena0011 week ago
int median(vector<vector<int>> &matrix, int r, int c){       // code here         int k=0;       int n=r*c;       int ans[n];       for(int i=0;i<r;i++)       {           for(int j=0;j<c;j++)           {               k=i*c+j;               ans[k]=matrix[i][j];                          }       }       sort(ans,ans+n);       int median =ans[n/2];       return median;   }
+3
mridulkapoor1234561 week ago
class Solution{   
public:
    int CountSmallerThanMid(vector<int>&row,int mid){
        int lo=0, hi=row.size()-1;
        while(lo<=hi){
            int md=(lo+hi)/2;
            if(row[md]<=mid)
                lo=md+1;
            else
                hi=md-1;
        }
        return lo;
    }

    int median(vector<vector<int>> &matrix, int r, int c){
        int lo=1;
        int hi=1e9;
        while(lo<=hi){
            int mid=(lo+hi)/2;
            int cnt=0;
            for(int i=0;i<r;i++){
                cnt+=CountSmallerThanMid(matrix[i],mid);
            }
            if(cnt<=r*c/2)
                lo=mid+1;
            else hi=mid-1;
        }
        return lo;
    }
};
0
iit20202182 weeks ago
bool helper(int mid,vector<vector<int>> &mat,int r,int c){       int n = r*c;       int ans1 = 0;       for(int i=0;i<r;i++){           int temp = upper_bound(mat[i].begin(),mat[i].end(),mid)-mat[i].begin();           ans1 += temp;       }       if(ans1 <= (n/2)){           return true;       }       return false;   }   int BinarySearch(int s,int e,vector<vector<int>> &mat, int r, int c){              int ans;       while((e-s)>1){           int mid = s+((e-s)/2);           if(helper(mid,mat,r,c)){               s=mid+1;               //ans=mid;           }else{               e=mid;               ans=mid;           }       }       if(!helper(s,mat,r,c))return s;       if(!helper(e,mat,r,c))return e;              return ans;   }   int median(vector<vector<int>> &mat, int r, int c){       // code here       int mini = 100000;       int maxi = 0;       for(int i=0;i<r;i++){           mini = min(mini,mat[i][0]);           maxi = max(maxi,mat[i][c-1]);       }       return BinarySearch(1,2000,mat,r,c);   }
 
 
Using BinarySearch in O(1) space and O(r*logc) complexity
+1
harshit68rocking2 weeks ago
   vector<int> merge(vector<int> &a, vector<int> &b){
        int m = a.size();
        int n= b.size();
        int i=0,j=0,k=0;
        vector<int> c(m+n);
        while(i<m && j<n){
            if(a[i]<=b[j]){
                c[k] = a[i]; i++;k++;
            }
            else if(a[i]>=b[j]){
                c[k] = b[j]; j++;k++;
            }
        }
        if(i<m){
            while(i<m){
                c[k] = a[i];i++;k++;
            }
        }
        if(j<n){
            while(j<n){
                c[k] = b[j];j++;k++;
            }
        }
        return c;
    }
    
    int median(vector<vector<int>> &matrix, int r, int c){
        // code here     
        vector<int> v;
        for(int i=0;i<r;i++){
            v = merge(v,matrix[i]);
        }
        return v[(r*c)/2];
    }
};
-4
yashvardhansingh20192 weeks ago
//Java Simple
       int k=0;       int[] ans = new int[r*c];       for(int i=0;i<r;i++){           for(int j=0;j<c;j++){               k = i*c+j;               ans[k] = matrix[i][j];           }       }       Arrays.sort(ans);       return ans[(r*c)/2];
-5
karthikbhatp3 weeks ago
class Solution {   int median(int matrix[][], int r, int c) {   List<Integer> list = new ArrayList<>();   for (int i = 0; i < r; i++) {    for (int j = 0; j < c; j++) {     list.add(matrix[i][j]);    }   }   int[] values = new int[list.size()];   for (int i = 0; i < list.size(); i++) {    values[i] = list.get(i);   }
   Arrays.sort(values);   int median;   int totalElements = values.length;   if (totalElements % 2 == 0) {    int sumOfMiddleElements = values[totalElements / 2] + values[totalElements / 2 - 1];    median =  sumOfMiddleElements / 2;   } else {    median =  values[values.length / 2];   }   return median;  }       }
-3
dibyendudey3033 weeks ago
Fast and Simple C++ solution:
class Solution{   
public:
    int median(vector<vector<int>> &matrix, int r, int c){
        // code here          
        vector<int> v;
        for(int i=0;i<r;i++)
        {
            for(int j=0;j<c;j++)
            {
                v.push_back(matrix[i][j]);
            }
        }
        sort(v.begin(),v.end());
        int pos=(v.size()/2);
        return v[pos];
    }
};
-3
arthurshelby4 weeks ago
😉🇮🇳✌️❄️
class Solution{   
public:
    int median(vector<vector<int>> &matrix, int r, int c){
        // code here   
        vector<int> vc;
        for(int i=0;i<r;i++){
            for(int j=0;j<c;j++){
                vc.push_back(matrix[i][j]);
            }
        }
        sort(vc.begin(),vc.end());
        
            return vc[vc.size()/2];
        }
    
};
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.