DEV Community

Wenqi Jiang
Wenqi Jiang

Posted on

378. Kth Smallest Element in a Sorted Matrix

Description

Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix.

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

You must find a solution with a memory complexity better than O(n2).

Example 1:

Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
Output: 13
Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input: matrix = [[-5]], k = 1
Output: -5
Enter fullscreen mode Exit fullscreen mode

Constraints:

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 300
  • 109 <= matrix[i][j] <= 109
  • All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order.
  • 1 <= k <= n2

Solutions

Solution 1

Intuition

  1. binary search this number
  2. search how many numbers are smaller than the mid, and count them as cnt
  3. if cnt ≥ k, means the kth smallest number is in left part, so r = mid , else search the right part

Code

class Solution {
public:
    int kthSmallest(vector<vector<int>>& matrix, int k) {
        int n = matrix.size();
        int l = matrix[0][0], r = matrix[n - 1][n - 1], mid;

        while (l < r) {
            int mid = l + r >> 1;
            int col = n - 1, cnt = 0;
            for (int row = 0; row < n; row++) {
                while (col >= 0 && matrix[row][col] > mid) col--;
                cnt += col + 1;
            }
            if (cnt >= k)
                r = mid;
            else
                l = mid + 1;
        }

        return l;
    }
};
Enter fullscreen mode Exit fullscreen mode

Complexity

  • Time: O(n)
  • Space: O(1)

Top comments (0)