Skip to content

visual walkthrough

Kth Smallest Element in a Sorted Matrix

MediumBinary Search on ValueReported at: MetaAmazonGoogle+5

Counting elements ≤ mid across a sorted matrix.

Solve on LeetCode

The idea

You can't binary search positions here (the matrix isn't one sorted list), but you can binary search the value.

"How many numbers are ≤ v?" grows with v, and sorted rows and columns let you count it with one staircase walk.

Complexity

approachtimespace
Flatten and sortO(n² log n)O(n²)
Binary search on the valueO(n log(max − min))O(1)

More walkthroughs