InferenceAI

Enter at least two characters to search.

Start free

Kth Smallest in a Sorted Grid

mediumBinary Search25 min25 XP

Every row and every column of the n×nn \times n matrix grid is sorted in ascending order. Return the k-th smallest value (counting duplicates).

Requirements

  • Better than flattening and sorting: binary search on the value range, or use a heap of size nn.

Constraints

  • 1≤n≤3001 \le n \le 300, 1≤k≤n21 \le k \le n^2

Examples

EXAMPLE WALKTHROUGHclassic

A guided view of the published example, not a trace of your code.

INPUT[[[1,5,9],[10,11,13],[12,13,15]],8]
TASKkth_smallest_in_sorted_grid()
EXPECTED OUTPUT13

Start with the input values shown in this example.

Example 1 of 3

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

Output: 13

Explanation: classic

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

Output: -5

Explanation: single

Input: grid = [[1,2],[1,3]], k = 2

Output: 1

Explanation: duplicates

Hint 1

For a value x, you can count the entries <= x in O(n) by walking from the bottom-left corner.

Hint 2

Binary search for the smallest x whose count is at least k.

Topics

DSABinary SearchPython