Math Fundamentals18 sections · 814 units
Open in Course

Kth Smallest - The Insight (Binary search on values)

Count elements below threshold

Binary search doesn't have to search indices. You can search the value space. Here, the smallest element is matrix[0][0]matrix[0][0] and the largest is matrix[n−1][n−1]matrix[n-1][n-1].

For any value midmid, you can count how many matrix elements are ≤mid\leq mid by walking from the bottom-left corner. If the count is <k< k, search higher values. If ≥k\geq k, search lower values.

This converges to the kk-th smallest element in O(nlog⁡(max−min))O(n \log(max - min)) time. The logarithm comes from halving the value range.