All problems

Problem 109

Kth Smallest in a Sorted Matrix

Medium · 20 pts · Matrix, Binary Search, Heap

Problem

You are given an N x N matrix in which every row is sorted from left to right and every column is sorted from top to bottom, both in non-decreasing order. Find the K-th smallest element of the matrix, counting duplicates separately. Putting all N² values in a list and sorting it works for these limits. A smarter method binary searches on the value: for a candidate x, count the elements <= x by walking from the bottom-left corner, which takes O(N) per count.

Input

First line: integers N and K. Next N lines: N integers each.

Output

Print the K-th smallest element.

Constraints

1 <= N <= 300; 1 <= K <= N * N; -1000000000 <= values <= 1000000000

Example input

3 8
1 5 9
10 11 13
12 13 15

Example output

13

Explanation

The values of the matrix in sorted order are 1 5 9 10 11 12 13 13 15. The 8th value in this list is the second 13, so the answer is 13.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Minimum Meeting Rooms Next: Count Smaller Numbers After Self