text: Kth smallest element in an array that contains A [ i ] exactly B [ i ] times | Function to find the Kth smallest element that contains A [ i ] exactly B [ i ] times ; Traverse the given array ; Stores the frequency of every elements ; Traverse the given array ; Initialize a variable to store the prefix sums ; Iterate over the range [ 0 , M ] ; Increment sum by freq [ i ] ; If sum is greater than or equal to K ; Return the current element as answer ; Return - 1 ; Given Input ; Function call
code: function KthSmallest ( A , B , N , K ) { let M = 0 ; for ( let i = 0 ; i < N ; i ++ ) { M = Math . max ( A [ i ] , M ) ; } let freq = Array . from ( { length : M + 1 } , ( _ , i ) => 0 ) ; for ( let i = 0 ; i < N ; i ++ ) { freq [ A [ i ] ] += B [ i ] ; } let sum = 0 ; for ( let i = 0 ; i <= M ; i ++ ) { sum += freq [ i ] ; if ( sum >= K ) { return i ; } } return - 1 ; } let A = [ 3 , 4 , 5 ] ; let B = [ 2 , 1 , 3 ] ; let N = A . length ; let K = 4 ; document . write ( KthSmallest ( A , B , N , K ) ) ;