Kth Smallest Element in a Sorted Matrix
Problem
You are given an n x n matrix of integers in which every row is sorted in ascending order and every column is sorted in ascending order. Rows do not necessarily chain into one another: the first element of a row may be smaller than the last element of the previous row. Given an integer k, return the k-th smallest value in the matrix, counting duplicates as separate entries (so the sorted order of all n^2 values, position k).
nis between 1 and 500.- Cell values are integers between -2,000,000,000 and 2,000,000,000.
kis between 1 andn^2.
Examples
matrix = [[2, 6, 8], [3, 7, 12], [9, 14, 20]], k = 5→8. Sorted values: 2, 3, 6, 7, 8, 9, 12, 14, 20; the 5th is 8.matrix = [[4]], k = 1→4.matrix = [[3, 5], [3, 8]], k = 2→3. Duplicates count separately, so the two 3s occupy positions 1 and 2.
Hints
- Flattening and sorting is O(n^2 log n). Which structural property is that throwing away?
- Every row is a sorted list; the k-th smallest across
nsorted lists is a merge problem. Alternatively: for a candidate valuex, how fast can you count matrix entries<= x? - Either a min-heap seeded with each row's first element (pop
ktimes), or binary search on the value range with an O(n) staircase count as the predicate.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.