Kth Smallest Element in a Sorted Matrix (LeetCode 378): Solution and Explanation

Medium
Array
Binary Search
Sorting
Heap
Matrix

In an n by n matrix whose rows and columns are both sorted in ascending order, find the value that would be k-th if every element were placed into one sorted list. Duplicates count separately.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The obvious approach is to dump all n² values into a list, sort it, and return the element at index k - 1. That is O(n² log n) time and O(n²) memory, and it ignores that the matrix is already heavily sorted. A min-heap that merges the rows like k sorted lists does better, at O(k log n), but it can still approach n² log n when k is large.

A different angle is to search over values rather than positions. The answer lies somewhere between the smallest element, matrix[0][0], and the largest, matrix[n-1][n-1]. For any candidate value x, ask how many elements are less than or equal to x. That count only grows as x grows, so it is monotonic, and the answer is the smallest x whose count reaches k. Monotonic plus smallest is a binary search.

The remaining question is how to count fast, and the sorted rows and columns make that linear. Start at the top-right corner. In row r, move left while the value is greater than x; everything from column 0 to the current column is then at most x, which is c + 1 elements. Moving down a row, the boundary can only move left or stay, because columns are sorted downward, so the pointer never moves right. The whole count takes O(n) steps.

Why is the found value actually in the matrix? The binary search returns the smallest x with a count of at least k. If x were not present, then x - 1 would have the same count, contradicting minimality. So the result is always a real element.

Approach: Binary search on value range

  1. Set l = matrix[0][0] and r = matrix[n - 1][n - 1], the smallest and largest values.
  2. While l <= r, take mid = (l + r) // 2.
  3. Count elements at most mid with countLessEqual: for each row, move a column pointer c left while matrix[r][c] > mid, then add c + 1.
  4. If the count is at least k, record res = mid and search lower values with r = mid - 1.
  5. Otherwise search higher values with l = mid + 1.
  6. Return res once the range is empty.

Step-by-step example

matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
  1. The value range is 1 to 15. For mid = 8, row 0 contributes 2 (1 and 5) and rows 1 and 2 contribute 0. The count is 2, less than 8, so l = 9.
  2. For mid = 12, row 0 gives 3, row 1 gives 2 (10 and 11), and row 2 gives 1 (12). The count is 6, so l = 13.
  3. For mid = 14, the rows give 3, 3 and 2, a count of 8. That reaches k, so res = 14 and r = 13.
  4. For mid = 13, the rows again give 3, 3 and 2 because both 13s count. The count is 8, so res = 13 and r = 12.
  5. Now l = 13 is greater than r = 12, so the search ends and returns 13.

Code: Python, Java, C++

1class Solution:
2    def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
3        n = len(matrix)
4        l, r = matrix[0][0], matrix[n - 1][n - 1]
5        res = -1
6        
7        while l <= r:
8            mid = (l + r) // 2
9            if self.countLessEqual(matrix, mid) >= k:
10                res = mid
11                r = mid - 1
12            else:
13                l = mid + 1
14        return res
15    
16    def countLessEqual(self, matrix, mid):
17        count = 0
18        c = len(matrix) - 1
19        for r in range(len(matrix)):
20            while c >= 0 and matrix[r][c] > mid:
21                c -= 1
22            count += (c + 1)
23        return count

Time and space complexity

Time

O(n log(max - min))

The binary search runs over the value range, taking log(max - min) iterations, and each iteration counts in O(n) with the staircase walk.

Space

O(1)

Only the search bounds and the counting pointers are stored.

Other approaches

Min-heap merge (time O(k log n), space O(n))

Push the first element of each row into a min-heap, then pop k times, each time pushing the next element from the popped element's row. It is intuitive when you think of rows as sorted lists and is fast for small k.

Flatten and sort (time O(n² log n), space O(n²))

Copy all n² values into one array and sort it. It is the easiest correct approach but ignores the structure and uses quadratic memory.

Common mistakes

  • Binary searching over indices instead of values. The k-th element's position is not determined by a simple index formula in this matrix.
  • Counting with < instead of <=, which mishandles duplicates and can skip the true answer.
  • Resetting the column pointer to the last column for every row, which turns the O(n) count into O(n²).
  • Computing the midpoint as (l + r) // 2 in Java or C++ with values near the integer limits, where l + (r - l) / 2 is safer.

Frequently asked questions

Why does binary search on values return an element that exists in the matrix?

The search finds the smallest value whose count of elements at or below it is at least k. If that value were missing from the matrix, the value one smaller would have the same count, which contradicts it being the smallest.

Heap or binary search for Kth Smallest Element in a Sorted Matrix?

A heap is O(k log n) and is simpler when k is small. Binary search on values is O(n log(max - min)) with constant extra space, which is better when k is large or memory is tight.

How do you count elements less than or equal to a value in O(n)?

Walk a pointer from the top-right corner. In each row, move left past values greater than the target, add the number of remaining columns, then go down a row without resetting the pointer.

Does this work if the matrix contains duplicates?

Yes. Duplicates are counted separately by the less-than-or-equal count, so the k-th smallest is found correctly even when the same value appears several times.