MediumArrayBinary SearchMatrix

Kth Smallest Element in a Sorted Matrix

LeetCode
1 approach, code in all languages

You are given an n x n grid of integers where each individual row reads in non-decreasing order from left to right, and each individual column reads in non-decreasing order from top to bottom. Note that this ordering guarantee applies within rows and within columns, not across the flattened grid as a whole.

Given a value k, return the k-th smallest number when all of the grid's entries are considered together. Duplicate values count as distinct positions, so the k-th smallest refers to the k-th entry in sorted order, not the k-th unique value.

Example 1

Input: matrix = [[1, 5, 9], [10, 11, 13], [12, 13, 15]], k = 8

Output: 13

Sorted, the entries are 1, 5, 9, 10, 11, 12, 13, 13, 15. The eighth value in that order is 13.

Example 2

Input: matrix = [[-5]], k = 1

Output: -5

The grid holds a single value, so the first smallest element is that value.

Constraints

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 300
  • -10^9 <= matrix[i][j] <= 10^9
  • 1 <= k <= n^2
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now