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 Matrix INPUT n x n sorted matrix 1 5 9 10 11 13 12 13 15 Rows sorted --> Cols sorted (down) Parameters matrix = [[1,5,9], [10,11,13],[12,13,15]] k = 8 Sorted: 1,5,9,10,11,12,13,13,15 ALGORITHM STEPS 1 Binary Search Setup lo = matrix[0][0] = 1 hi = matrix[n-1][n-1] = 15 2 Find Mid Value mid = (lo + hi) / 2 Count elements <= mid 3 Count Function Start bottom-left corner Move right if val <= mid Move up if val > mid 4 Adjust Search if count < k: lo = mid + 1 else: hi = mid Return lo when lo == hi Time: O(n log(max-min)) Space: O(1) FINAL RESULT Binary Search Trace: lo=1, hi=15, mid=8 count(8)=5 < 8, lo=9 lo=9, hi=15, mid=12 count(12)=7 < 8, lo=13 lo=13, hi=15, mid=14 count(14)=9 >= 8, hi=14 lo=13, hi=14, mid=13 count(13)=8 >= 8, hi=13 lo == hi == 13 OUTPUT 13 8th smallest = 13 [1,5,9,10,11,12,13,13,15] OK - Verified! Key Insight: Instead of sorting all n^2 elements, use binary search on the VALUE RANGE [min, max]. For each candidate value, count elements <= mid in O(n) time using the sorted property: traverse from bottom-left, moving right when value <= mid, up when value > mid. TutorialsPoint - Kth Smallest Element in a Sorted Matrix | Binary Search Approach
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