← Questions

Kth smallest element in a sorted matrix

0
MetaCodingLast asked Sep 2025

A coding interview question asked in Meta's AI-enabled coding round, last asked Sep 2025. It tests heaps, binary-search and matrices.

Every row and every column of an n x n matrix is sorted in non-decreasing order. Return the k-th smallest value in the matrix, counting duplicates.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • kth_smallest(matrix: list[list[int]], k: int) -> int — 1 <= k <= n². The k-th value of the matrix in sorted order, not the k-th distinct value.

Example

kth_smallest([[1, 5, 9], [10, 11, 13], [12, 13, 15]], 8)   ->  13   # 1 5 9 10 11 12 13 13 15
kth_smallest([[1, 2], [1, 3]], 2)                            ->  1    # duplicates count: 1 1 2 3

Constraints

  • 1 <= n <= 300, -10^9 <= matrix[i][j] <= 10^9.
  • Aim for better than O(n² log n) time and less than O(n²) extra memory.

Clarifying questions

  • Do duplicates count toward k?
  • Is the matrix always square?
  • Is k usually small, or can it be close to n²?

What a strong answer covers

  • A min-heap holding the head of each row: pop k times, pushing the next value of the same row each time. O(k log n) time, O(n) memory.
  • Binary search on the value range: for a candidate x, count the entries <= x in O(n) by walking from the bottom-left corner. Shrink to the smallest x with a count of at least k. O(n log(max - min)) time, O(1) memory.
  • Why the binary search always lands on a value that is in the matrix.
  • When each one wins: a small k, a huge value range, very large n.
  • Tests: k = 1, k = n², all values equal, negative values.

Follow-ups

  • Rows are sorted but columns are not.
  • The matrix is m x n instead of square.
  • Find the median of the matrix.

Where it's asked

  • Meta · AI-enabled coding · Last asked Sep 202560 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it

What it tests

heaps · binary-search · matrices

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding