Math Fundamentals18 sections · 814 units
Open in Course

Problem - Find Kth Smallest (Fourth problem)

LeetCode 378

Given an n×nn \times n matrix where each row and column is sorted in ascending order, find the kk-th smallest element.

The naive approach is to flatten the matrix, sort it, and pick the kk-th element. That takes O(n2logn)O(n^2 \log n) time.

But you can use binary search on the value range (not the indices). The answer lies between the smallest and largest elements, and you can count how many elements are smaller than a given value. Think about how logarithms appear here.