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.
How to Solve
Algorithm
- Start with
left = minOfMatrix = matrix[0][0]
andright = maxOfMatrix = matrix[n-1][n-1]
. - Find the
mid
of theleft
and theright
. This middle number is NOT necessarily an element in the matrix. - If
countLessOrEqual(mid) >= k
, we keep currentans = mid
and try to find smaller value by searching on the left side. Otherwise, we search on the right side. - Since
ans
is the smallest value whichcountLessOrEqual(ans) >= k
, so it’s the kth smallest element in the matrix.
How to count number of elements less or equal to x efficiently?
- Since our
matrix
is sorted in ascending order by rows and columns. - We use two pointers, one points to the rightmost column
c = n-1
, and one points to the lowest rowr = 0
.- If
matrix[r][c] <= x
then the number of elements in rowr
less or equal tox
is(c+1)
(Becauserow[r]
is sorted in ascending order, so ifmatrix[r][c] <= x
thenmatrix[r][c-1]
is also <=x
). Then we go to next row to continue counting. - Else if
matrix[r][c] > x
, we decrease column c untilmatrix[r][c] <= x
(Because column is sorted in ascending order, so ifmatrix[r][c] > x
thenmatrix[r+1][c]
is also >x
).
- If
- Time complexity for counting:
O(M+N)
.
Test Cases
Input:
(int[]) matrix = [[1,5,9],[10,11,13],[12,13,15]]
(int) k = 8
Output:
(int) 13
Explanation:
The elements in the matrix are [1,5,9,10,11,12,13,13,15],
and the 8th smallest number is 13