Kth Smallest Element in a Sorted Matrix
Master this topic with zero to advance depth.
Kth Smallest Element in a Sorted Matrix
Given an n x n matrix where each of the rows and columns are sorted in ascending order, return the k-th smallest element.
Examples
Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
Output: 13
Approach 1
Level I: Min-Heap (K-Way Merge)
Intuition
This is equivalent to merging sorted lists. Use a min-heap to pick the smallest available element times.
⏱ $O(K \\log N)$💾 $O(N)$
Detailed Dry Run
matrix = [[1,5,9],[10,11,13],[12,13,15]], k=8 Heap: [(1,0,0), (10,1,0), (12,2,0)] Pop (1,0,0) -> Push (5,0,1). Pop (5,0,1) -> Push (9,0,2). ... 8th pop = 13.
Approach 2
Level III: Optimal (Binary Search on Answer)
Intuition
The value space is [matrix[0][0], matrix[n-1][n-1]]. For a value mid, we can count elements mid in by starting from the bottom-left corner.
⏱ $O(N \\cdot \\log(Max - Min))$💾 $O(1)$
Detailed Dry Run
| Step | L | R | Mid | Count | Decision |
|---|---|---|---|---|---|
| 1 | 1 | 15 | 8 | 2 | L = 9 |
| 2 | 9 | 15 | 12 | 6 | L = 13 |
| 3 | 13 | 15 | 14 | 9 | R = 14 |
| Exit | - | - | - | - | Return 13 |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.