378. Kth Smallest Element in a Sorted Matrix

// time: O((m + n) * log(max - min)); space: O(1)Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

Example:

matrix = [
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
],
k = 8,

return 13.

Note: You may assume k is always valid, 1 ≤ k ≤ n2.

// Priority queue
int kthSmallest(vector<vector<int>>& matrix, int k) {
    auto cmp = [] (const vector<int>& a, const vector<int>& b) {
        return a[2] > b[2];  
    };
    priority_queue<vector<int>, vector<vector<int> >, decltype(cmp) > pq(cmp);
    for (int j = 0; j < matrix[0].size(); ++j) pq.push({0, j, matrix[0][j]});
    for (int i = 0; i < k - 1; ++i) {
        vector<int> t = pq.top(); pq.pop();
        if (t[0] == matrix.size() - 1) continue;
        int row_idx = t[0] + 1;
        pq.push({row_idx, t[1], matrix[row_idx][t[1]]});
    }
    return pq.top()[2];
}
// Binary Search
int kthSmallest(vector<vector<int>>& matrix, int k) { // time: O((m + n) * log(max - min)); space: O(1)
    // Binary search in range [l, r)
    int l = matrix.front().front(), r = matrix.back().back() + 1;
    while (l < r) {
        int mid = l + (r - l) / 2, cnt = 0, j = matrix[0].size() - 1;
        for (int i = 0; i < matrix.size(); ++i) {
            while (j >= 0 && matrix[i][j] > mid) --j;
            cnt += (j + 1);
        }
        if (cnt < k) l = mid + 1;
        else r = mid;
    }
    return r;
}

Last updated

Was this helpful?