Minimize steps to form string S from any random string of length K using a fixed length subsequences | Function to find the minimum number of string required to generate the original string ; Stores the frequency of each character of String S ; Iterate over the range [ 0 , 25 ] ; Stores the frequency of each character of String S ; Count unique characters in S ; If unique characters is greater then N , then return - 1 ; Otherwise ; Perform Binary Search ; Find the value of mid ; Iterate over the range [ 0 , 26 ] ; If the amount [ i ] is greater than 0 ; Update the ranges ; Find the resultant string ; Generate the subsequence ; If the length of resultant string is less than N than add a character ' a ' ; Print the string ; Driver Code
function findString ( S , N ) { let amounts = new Array ( 26 ) ; for ( let i = 0 ; i < 26 ; i ++ ) { amounts [ i ] = 0 ; } for ( let i = 0 ; i < S . length ; i ++ ) { amounts [ S [ i ] . charCodeAt ( 0 ) - 97 ] ++ ; } let count = 0 ; for ( let i = 0 ; i < 26 ; i ++ ) { if ( amounts [ i ] > 0 ) count ++ ; } if ( count > N ) { document . write ( " " ) ; } else { let ans = " " ; let high = 100001 ; let low = 0 ; let mid , total ; while ( high - low > 1 ) { total = 0 ; mid = Math . floor ( ( high + low ) / 2 ) ; for ( let i = 0 ; i < 26 ; i ++ ) { if ( amounts [ i ] > 0 ) { total += Math . floor ( ( amounts [ i ] - 1 ) / mid + 1 ) ; } } if ( total <= N ) { high = mid ; } else { low = mid ; } } document . write ( high + " " ) ; total = 0 ; for ( let i = 0 ; i < 26 ; i ++ ) { if ( amounts [ i ] > 0 ) { total += Math . floor ( ( amounts [ i ] - 1 ) / high + 1 ) ; for ( let j = 0 ; j < Math . floor ( ( amounts [ i ] - 1 ) / high + 1 ) ; j ++ ) { ans += String . fromCharCode ( i + 97 ) ; } } } for ( let i = total ; i < N ; i ++ ) { ans += " " ; } ans = ans . split ( " " ) . reverse ( ) . join ( " " ) ; document . write ( ans ) ; } } let S = " " ; let K = 4 ; findString ( S , K ) ;