Skip to content
BytePatterns

Kth Smallest In Matrix

MediumTwo Heaps & K-Way Merge#k-way-merge#heap~30m

Problem

You are given a square grid whose every row is sorted left to right and whose every column is sorted top to bottom. Return the k-th smallest value when all the cells are considered as one collection. Duplicates count separately, so the third smallest of 1, 1, 2 is 2.

Examples

Input:  matrix = [[1, 5, 9], [10, 11, 13], [12, 13, 15]], k = 8
Output: 13
Why:    in order the cells read 1, 5, 9, 10, 11, 12, 13, 13, 15
Input:  matrix = [[1, 2], [1, 3]], k = 3
Output: 2
Why:    duplicates are counted separately, so the order is 1, 1, 2, 3
Input:  matrix = [[-5]], k = 1
Output: -5
Why:    edge case, a single cell

Hints

0 / 3

Stuck on the idea rather than the code? Kth Smallest in a Matrix covers it.