← Questions
Kth smallest element in a sorted matrix
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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². Thek-th value of the matrix in sorted order, not thek-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
kusually small, or can it be close ton²?
What a strong answer covers
- A min-heap holding the head of each row: pop
ktimes, 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<= xin O(n) by walking from the bottom-left corner. Shrink to the smallestxwith a count of at leastk. 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 largen. - Tests:
k = 1,k = n², all values equal, negative values.
Follow-ups
- Rows are sorted but columns are not.
- The matrix is
m x ninstead 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
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
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
