Striver-SDE-Sheet

Repository containing solution for #SdeSheetChallenge by striver

View the Project on GitHub

Matrix Median

You have been given a matrix of ‘N’ rows and ‘M’ columns filled up with integers where every row is sorted in non-decreasing order. Your task is to find the overall median of the matrix i.e if all elements of the matrix are written in a single line, then you need to return the median of that linear array. The median of a finite list of numbers is the “middle” number when those numbers are listed in order from smallest to greatest. If there is an odd number of observations, the middle one is picked. For example, consider the list of numbers [1, 3, 3, 6, 7, 8, 9]. This list contains seven numbers. The median is the fourth of them, which is 6.

Brute force

Code

int getMedian(vector<vector<int>>& matrix)
{
    vector<int> ans;
    int n = matrix.size(), m = matrix[0].size();
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            ans.push_back(matrix[i][j]);
        }
    }
    n = ans.size();
    sort(ans.begin(), ans.end());
    return ans[(n / 2)];
}

Code

int getMedian(vector<vector<int>>& matrix)
{
    int n = matrix.size();
    int m = matrix[0].size();

    int mn = INT_MAX, mx = INT_MIN;
    for (int i = 0; i < n; i++) {
        // Get min element
        if (matrix[i][0] < mn)
            mn = matrix[i][0];

        // Get max element
        if (matrix[i][m - 1] > mx)
            mx = matrix[i][m - 1];
    }

    int reqCount = (n * m + 1) / 2;
    while (mn < mx) {
        int mid = mn + (mx - mn) / 2;
        int count = 0;

        // count elements smaller that or equal to mid
        for (int i = 0; i < n; i++) {
            count += upper_bound(matrix[i].begin(), matrix[i].end(), mid) - matrix[i].begin();
        }

        if (count < reqCount)
            mn = mid + 1;
        else
            mx = mid;
    }
    return mn;
}