Problem Description
Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix. Note that it is the kth smallest element in the sorted order (not the kth distinct element).
Key Insights
- The matrix is sorted both row-wise and column-wise.
- Instead of flattening and sorting the entire matrix (which uses O(n^2) space), take advantage of the sorted properties.
- Binary search can be applied over the range of values in the matrix.
- Count the number of elements less than or equal to a midpoint to determine if the kth element is on the left or right side of the search range.
- Alternatively, a min-heap approach can be used, though it generally leads to higher space complexity.
Space and Time Complexity
Time Complexity: O(n * log(max - min)), where max and min represent the range of values in the matrix. Space Complexity: O(1) extra space (ignoring recursion and input).
Solution
We solve the problem by performing binary search on the value range between the smallest and largest elements in the matrix. For a mid-value during the binary search, we count how many elements in the matrix are less than or equal to mid by scanning from the bottom-left corner. If the count is less than k, we move to the right half of the range; otherwise, we adjust the range to the left. This iterative process continues until the range is narrowed down to a single element, which is the kth smallest.