Kth Smallest Element in a Sorted Matrix - Problem
Find the Kth Smallest Element in a Sorted Matrix
You're given an
๐ฏ Goal: Return the kth smallest value (not kth distinct value)
๐ Input: A sorted nรn matrix and integer k
๐ Output: The kth smallest element
Important: You must solve this with memory complexity better than O(nยฒ) - you cannot simply flatten the matrix into an array!
Example:
You're given an
n ร n matrix where both rows and columns are sorted in ascending order. Your task is to find the kth smallest element in the entire matrix.๐ฏ Goal: Return the kth smallest value (not kth distinct value)
๐ Input: A sorted nรn matrix and integer k
๐ Output: The kth smallest element
Important: You must solve this with memory complexity better than O(nยฒ) - you cannot simply flatten the matrix into an array!
Example:
Matrix: [[1,5,9],[10,11,13],[12,13,15]]k = 8Output: 13 (the 8th smallest element) Input & Output
example_1.py โ Basic Case
$
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 element is 13.
example_2.py โ Small Matrix
$
Input:
matrix = [[-5]], k = 1
โบ
Output:
-5
๐ก Note:
There's only one element in the matrix, so the 1st smallest is -5.
example_3.py โ First Element
$
Input:
matrix = [[1,2],[1,3]], k = 1
โบ
Output:
1
๐ก Note:
The elements in sorted order are [1,1,2,3]. The 1st smallest element is 1.
Visualization
Tap to expand
Understanding the Visualization
1
Naive Approach
Collect all elements and sort them - requires O(nยฒ) space
2
Min-Heap Approach
Use a heap to track only the k smallest candidates we've seen
3
Binary Search Magic
Search on VALUES not positions - count elements โค candidate value
4
Efficient Counting
Use sorted property: start bottom-left, move systematically
Key Takeaway
๐ฏ Key Insight: Binary search on the VALUE RANGE combined with efficient counting using the sorted matrix property gives us optimal O(n log(max-min)) time and O(1) space complexity!
Time & Space Complexity
Time Complexity
O(k log k)
We pop k elements from heap, each operation takes O(log k) time
โก Linearithmic
Space Complexity
O(min(k, n))
Heap stores at most min(k, n) elements plus visited set
โก Linearithmic Space
Constraints
- n == matrix.length == matrix[i].length
- 1 โค n โค 300
- 1 โค k โค n2
- -109 โค matrix[i][j] โค 109
- All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code