Skip to content
Decoder

Kth Smallest Element in a Sorted Matrix

Medium

Problem

You are given an n x n grid matrix where every row and every column is sorted in ascending order. Return the `k`th smallest value in the grid, counting duplicates (it is the kth value in sorted order, not the kth distinct value). Aim for better than O(n²) memory.

Example 1

matrix = [[1,  5,  9],

Example 2

          [10, 11, 13],

Example 3

Input
[12, 13, 15]], k = 8
Output
13

Example 4

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

Constraints

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 300
  • -10^9 <= matrix[i][j] <= 10^9
  • 1 <= k <= n^2

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.