Kth Smallest Element of a Matrix of given dimensions filled with product of indices | C # program to implement the above approach ; 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
using System ; class GFG { public static bool countLessThanMid ( int mid , int N , int M , int K ) { int count = 0 ; for ( int i = 1 ; i <= Math . Min ( N , mid ) ; ++ i ) { count = count + Math . Min ( mid / i , M ) ; } if ( count >= K ) return false ; else return true ; } public static int findKthElement ( int N , int M , int K ) { int low = 1 , high = N * M ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( countLessThanMid ( mid , N , M , K ) ) low = mid + 1 ; else high = mid - 1 ; } return high + 1 ; } public static void Main ( String [ ] args ) { int N = 2 , M = 3 ; int K = 5 ; Console . WriteLine ( findKthElement ( N , M , K ) ) ; } }