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(n2).

&nbsp;
Example 1:

Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
Output: 13
Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13


Example 2:

Input: matrix = [[-5]], k = 1
Output: -5


&nbsp;
Constraints:


	n == matrix.length == matrix[i].length
	1 &lt;= n &lt;= 300
	-109 &lt;= matrix[i][j] &lt;= 109
	All the rows and columns of matrix are guaranteed to be sorted in non-decreasing order.
	1 &lt;= k &lt;= n2


&nbsp;
Follow up:


	Could you solve the problem with a constant memory (i.e., O(1) memory complexity)?
	Could you solve the problem in O(n) time complexity? The solution may be too advanced for an interview but you may find reading this paper fun.


class Solution:
    def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
        return sorted(list(sum(matrix, [])))[k-1]
/**
 * Using PriorityQueue
 *
 * Time Complexity:
 *      O(min(N,K)*log(min(N,K))) -> To add initial min(N,K) elements, as we are adding the elements individually.
 *                                   If we were adding all elements in one go, then the complexity would be O(min(N,K))
 *                                   Refer: https://stackoverflow.com/a/34697891
 *      O(2*(K-1)*log(min(N,K)) -> To poll K-1 elements and add next K-1 elements.
 * Total Time Complexity: O((min(N,K) + 2*(K-1)) * log(min(N,K)) = O(K * log(min(N,K))
 *
 * Space Complexity: O(min(N, K))
 *
 * N = Length of one side of the matrix. K = input value k.
 */
class Solution {
    public int kthSmallest(int[][] matrix, int k) {
        if (matrix == null || k <= 0) {
            throw new IllegalArgumentException("Input is invalid");
        }

        int n = matrix.length;
        if (k > n * n) {
            throw new NoSuchElementException("k is greater than number of elements in matrix");
        }
        if (k == 1) {
            return matrix[0][0];
        }
        if (k == n * n) {
            return matrix[n - 1][n - 1];
        }

        PriorityQueue<int[]> queue = new PriorityQueue<>((a, b) -> (matrix[a[0]][a[1]] - matrix[b[0]][b[1]]));

        for (int i = 0; i < Math.min(n, k); i++) {
            queue.offer(new int[] { i, 0 });
        }
        while (k > 1) {
            int[] cur = queue.poll();
            if (cur[1] < n - 1) {
                cur[1]++;
                queue.offer(cur);
            }
            k--;
        }

        return matrix[queue.peek()[0]][queue.peek()[1]];
    }
}
class Solution {
public:
    int kthSmallest(vector<vector<int>>& matrix, int k) {
        int n = matrix.size(), start = matrix[0][0], end = matrix[n-1][n-1];
        unordered_map<int, int>mp;
        for(int i = 0; i < n; i++)
            for(int j = 0; j < n; j++)
                mp[matrix[i][j]]++;
        
        for(int i = start; i <= end; i++)
            if(mp.find(i) != mp.end()){
                for(int j = 0; j < mp[i]; j++){
                    k--;
                    if(k == 0) return i;
                }
            }
          return -1;  
    }
};
var kthSmallest = function(matrix, k) {
    let arr = matrix.flat()
    arr.sort((a,b)=>a-b)
    return arr[k-1]
};
Kth Smallest Element in a Sorted Matrix