Kth Smallest Element in a Sorted Matrix - Problem
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.
You must find a solution with a memory complexity better than O(n²).
Input & Output
Example 1 — Basic 3x3 Matrix
$
Input:
matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
›
Output:
13
💡 Note:
The elements in sorted order are [1,5,9,10,11,12,13,13,15]. The 8th smallest is 13.
Example 2 — Small Matrix
$
Input:
matrix = [[-5]], k = 1
›
Output:
-5
💡 Note:
Single element matrix, the 1st (and only) smallest element is -5.
Example 3 — First Element
$
Input:
matrix = [[1,2],[1,3]], k = 1
›
Output:
1
💡 Note:
Elements in order: [1,1,2,3]. The 1st smallest is 1 (top-left).
Constraints
- n == matrix.length == matrix[i].length
- 1 ≤ n ≤ 300
- -109 ≤ matrix[i][j] ≤ 109
- All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order
- 1 ≤ k ≤ n2
Visualization
Tap to expand
Understanding the Visualization
1
Input
Sorted matrix and k=8
2
Process
Find 8th smallest efficiently
3
Output
Return the element value
Key Takeaway
🎯 Key Insight: Instead of sorting all elements, leverage the matrix's sorted structure to find the kth smallest efficiently using binary search on answer values or heap-based selection.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code