4
* <p>Time Complexity: O(min(N,K)*log(min(N,K))) -> To add initial min(N,K) elements, as we are5
* adding the elements individually. If we were adding all elements in one go, then the complexity6
* would be O(min(N,K)) Refer: https://stackoverflow.com/a/34697891 O(2*(K-1)*log(min(N,K)) -> To7
* poll K-1 elements and add next K-1 elements. Total Time Complexity: O((min(N,K) + 2*(K-1)) *8
* log(min(N,K)) = O(K * log(min(N,K))10
* <p>Space Complexity: O(min(N, K))12
* <p>N = Length of one side of the matrix. K = input value k.15
public int kthSmallest(int[][] matrix, int k) {16
if (matrix == null || k <= 0) {17
throw new IllegalArgumentException("Input is invalid");20
int n = matrix.length;22
throw new NoSuchElementException("k is greater than number of elements in matrix");28
return matrix[n - 1][n - 1];31
PriorityQueue<int[]> queue =32
new PriorityQueue<>((a, b) -> (matrix[a[0]][a[1]] - matrix[b[0]][b[1]]));34
for (int i = 0; i < Math.min(n, k); i++) {35
queue.offer(new int[] {i, 0});38
int[] cur = queue.poll();46
return matrix[queue.peek()[0]][queue.peek()[1]];