Kth Smallest Element in a Sorted Matrix - Problem
Find the Kth Smallest Element in a Sorted Matrix

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 = 8
Output: 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
Kth Smallest Element: Solution ComparisonโŒ Naive O(nยฒ) Space:159โ†’ [1,5,9,10,11,12,13,13,15]Store all nยฒ elementsโšก Min-Heap O(k) Space:1510Heap stores โ‰ค k elementsSmart but still O(k log k) time๐ŸŽฏ Binary Search O(1) Space:115Search on VALUESBinary search: O(n log(max-min)) timeCounting Technique:159101113121315For target=12:Green: โ‰ค 12 โœ“Yellow: โ‰ค 12 โœ“Red: > 12 โœ—Start here, count efficiently
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

n
2n
โšก Linearithmic
Space Complexity
O(min(k, n))

Heap stores at most min(k, n) elements plus visited set

n
2n
โšก 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
Asked in
Google 42 Amazon 38 Meta 25 Microsoft 31
58.3K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen