sagelearnai

Kth Smallest Element in a Sorted Matrix

Difficulty: Medium · Pattern: Binary Search · LeetCode #378

In an n × n matrix where each row and each column is sorted ascending, return the k-th smallest element (counting duplicates).

Examples

text
matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8  →  13
matrix = [[-5]], k = 1                          →  −5

Hints

  1. Binary search over values between matrix[0][0] and matrix[n−1][n−1].
  2. Count how many elements are ≤ mid in O(n) by walking from the bottom-left corner.

Approach

Search the value range [lo, hi]. For a candidate mid, count the elements ≤ mid with a staircase: start at the bottom-left; if the value is ≤ mid, the whole column segment above counts (row + 1), so move right; else move up. If count ≥ k, the answer is ≤ mid (hi = mid); else lo = mid + 1. The final lo is guaranteed to be a matrix value. O(n log(range)). (A min-heap gives O(k log n).)

Complexity

Time: O(n · log(max − min)). Space: O(1).

Python solution
def kthSmallest(matrix, k):
    n = len(matrix)
    def count_le(x):
        r, c, cnt = n - 1, 0, 0
        while r >= 0 and c < n:
            if matrix[r][c] <= x:
                cnt += r + 1; c += 1
            else:
                r -= 1
        return cnt
    lo, hi = matrix[0][0], matrix[-1][-1]
    while lo < hi:
        mid = (lo + hi) // 2
        if count_le(mid) >= k:
            hi = mid
        else:
            lo = mid + 1
    return lo
JavaScript solution
function kthSmallest(matrix, k) {
  const n = matrix.length;
  const countLe = (x) => { let r = n - 1, c = 0, cnt = 0; while (r >= 0 && c < n) { if (matrix[r][c] <= x) { cnt += r + 1; c++; } else r--; } return cnt; };
  let lo = matrix[0][0], hi = matrix[n - 1][n - 1];
  while (lo < hi) { const mid = Math.floor((lo + hi) / 2); if (countLe(mid) >= k) hi = mid; else lo = mid + 1; }
  return lo;
}