oneby7

Binary Search Searching a matrix

255. Kth Smallest Element in a Sorted Matrix

Medium

You are given a square grid of integers matrix with n rows and n columns. Every row is sorted from left to right, and every column is sorted from top to bottom, both in non-decreasing order.

Return the k-th smallest value in the grid. Picture all n2 values written out in one sorted list: the answer is the value at position k of that list, counting from 1. Equal values each take their own place in the list, so the answer is the k-th smallest value, not the k-th smallest distinct value.

Example 1

259481271015

Input: matrix = [[2, 5, 9], [4, 8, 12], [7, 10, 15]], k = 5

Output: 8

Explanation: In sorted order the values are 2, 4, 5, 7, 8, 9, 10, 12, 15. The fifth of them is 8.

Example 2

-6-6-1-603-233

Input: matrix = [[-6, -6, -1], [-6, 0, 3], [-2, 3, 3]] k = 4

Output: -2

Explanation: The three copies of -6 take the first three places, so the fourth smallest value is -2.

Example 3

−10⁹7310⁹

Input: matrix = [[-1000000000, 7], [3, 1000000000]], k = 4

Output: 1000000000

Explanation: The grid has four cells, so the fourth smallest value is the largest one.

Check your understanding

Work out the answer for this input before you write any code.

matrix = [[2, 5, 8], [2, 5, 9], [4, 6, 10]], k = 7

Constraints

  • n == matrix.length == matrix[i].length
  • 1 ≤ n ≤ 400
  • -109 ≤ matrix[i][j] ≤ 109
  • Every row and every column of matrix is sorted in non-decreasing order.
  • 1 ≤ k ≤ n2

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.