Kth Smallest Element of a Matrix of given dimensions filled with product of indices | Function that returns true if the count of elements is less than mid ; To store count of elements less than mid ; Loop through each row ; Count elements less than mid in the ith row ; Function that returns the Kth smallest element in the NxM Matrix after sorting in an array ; Initialize low and high ; Perform binary search ; Find the mid ; Check if the count of elements is less than mid ; Return Kth smallest element of the matrix ; Driver Code
function countLessThanMid ( mid , N , M , K ) { let count = 0 ; for ( let i = 1 ; i <= Math . min ( N , mid ) ; ++ i ) { count = count + Math . min ( parseInt ( mid / i ) , M ) ; } if ( count >= K ) return false ; else return true ; } function findKthElement ( N , M , K ) { let low = 1 , high = N * M ; while ( low <= high ) { let mid = low + parseInt ( ( high - low ) / 2 ) ; if ( countLessThanMid ( mid , N , M , K ) ) low = mid + 1 ; else high = mid - 1 ; } return high + 1 ; } let N = 2 , M = 3 ; let K = 5 ; document . write ( findKthElement ( N , M , K ) ) ;