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
Kth Smallest Element in Sorted MatrixInput Matrix (sorted rows & cols)159101113121315k = 8Conceptual Sorted Order1591011121313151st2nd3rd4th5th6th7th8th9thChallenge: Find 8th smallest WITHOUT sorting all elements✓ Use matrix's sorted property✓ Memory better than O(n²)✓ Efficient algorithms: Min Heap or Binary SearchOutput: 13
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.
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
78.5K Views
Medium Frequency
~25 min Avg. Time
3.2K 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