Skip to the code
+25 XP

#389 K-th Smallest in a Sorted Price Grid

medium

A pricing page shows an n by n grid of plan prices where every row is sorted from left to right and every column is sorted from top to bottom.

Write kthSmallest(grid, k) that returns the k-th smallest price in the whole grid, counting repeated prices separately (k = 1 is the smallest). Try not to sort all n^2 prices.

Example 1

Input: grid = [[1,4,8],[6,9,13],[11,14,16]], k = 5
Output: 9

In order the prices are 1, 4, 6, 8, 9, 11, 13, 14, 16; the 5th is 9.

Example 2

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

One price.

Constraints

  • 1 <= n <= 300
  • 1 <= k <= n^2
  • -10^9 <= grid[i][j] <= 10^9
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).