You are given an n x n matrix where every row is sorted in ascending order and every column is also sorted in ascending order.
Return the kth smallest element in the matrix. Count duplicates as separate positions in sorted order.
Input / output
matrix: int[][], k: intkth smallest integerExamples
matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8 returns 13.matrix = [[-5]], k = 1 returns -5.matrix = [[1,2],[1,3]], k = 2 returns 1 because duplicates still occupy separate ranks.Constraints
1 <= n <= 300-10^9 <= matrix[i][j] <= 10^91 <= k <= n * nEdge cases
k can be 1 or n * n.Target complexity
O(n log(value range)) time and O(1) extra space.Hints
mid, count how many matrix entries are <= mid in O(n) time by walking from the bottom-left corner.Follow-up How would the trade-offs change if you used a min-heap that merges rows instead of binary-searching the value range?