A monitoring grid stores readings in a matrix with R rows and C columns. Every row is sorted in non-decreasing order from left to right, and every column is sorted in non-decreasing order from top to bottom. Values may repeat.
Given k (1-indexed), print the k-th smallest value among all R * C cells, counting repeated values with multiplicity (so if the two smallest cells are both 3, the 1st and 2nd smallest are both 3).
Line 1: two integers R and C.
Next R lines: each has C space-separated integers, a row of the matrix.
Last line: an integer k.
A single integer: the k-th smallest value in the matrix.
Example 1
Input
3 3 1 4 7 2 5 8 3 6 9 5
Expected
5
Explanation
Sorted, all nine values are 1..9; the 5th smallest is 5.
Example 2
Input
2 2 1 3 2 4 3
Expected
3
Explanation
The values in order are 1, 2, 3, 4; the 3rd smallest is 3.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →