matrix
binary-search

You are given an n x n matrix where every row is sorted in ascending order and every column is also sorted in ascending order.

Return the kth smallest element in the matrix. Count duplicates as separate positions in sorted order.

Input / output

  • Input: matrix: int[][], k: int
  • Output: the kth smallest integer

Examples

  1. matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8 returns 13.
  2. matrix = [[-5]], k = 1 returns -5.
  3. matrix = [[1,2],[1,3]], k = 2 returns 1 because duplicates still occupy separate ranks.

Constraints

  • 1 <= n <= 300
  • -10^9 <= matrix[i][j] <= 10^9
  • Each row and each column is sorted ascending.
  • 1 <= k <= n * n

Edge cases

  • The answer may appear multiple times in the matrix.
  • Negative values are allowed.
  • k can be 1 or n * n.

Target complexity

  • Aim for O(n log(value range)) time and O(1) extra space.

Hints

  1. Binary-search the answer value, not the index.
  2. For a candidate value mid, count how many matrix entries are <= mid in O(n) time by walking from the bottom-left corner.

Follow-up How would the trade-offs change if you used a min-heap that merges rows instead of binary-searching the value range?

Examples

Example 1

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

Example 2

Input: matrix = [[-5]], k = 1
Output: -5

Example 3

Input: matrix = [[1,2],[1,3]], k = 2
Output: 1
🔒 5 hidden

Running will execute all 8 cases, including 5 hidden ones.