Kth Smallest Element in a Sorted Matrix

MediumBinary Searchbinary search on answer

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an n x n integer matrix in which **every row and every column is sorted in non-decreasing order**. Return the k-th smallest value in the whole matrix. Count duplicates separately: if you listed all n² values in sorted order, the answer is the value at 1-based position k. Use less than O(n²) extra memory. O(n log(max - min)) time is achievable.

Examples

Input: matrix = [[1,4,9],[3,6,11],[8,10,15]], k = 5
Output: 8
In sorted order the values are 1, 3, 4, 6, 8, 9, 10, 11, 15, so the 5th smallest is 8.
Input: matrix = [[-3,-1],[-2,2]], k = 3
Output: -1
Sorted: -3, -2, -1, 2. The 3rd is -1.

Constraints

  • 1 <= n <= 300
  • -10^9 <= matrix[i][j] <= 10^9
  • Every row and column is sorted in non-decreasing order.
  • 1 <= k <= n²

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More binary search on answer problems