Construct a string that has exactly K subsequences from given string | Function that computes the string s ; Length of the given string str ; List that stores all the prime factors of given k ; Find the prime factors ; Initialize the count of each character position as 1 ; Loop until the list becomes empty ; Increase the character count by multiplying it with the prime factor ; If we reach end then again start from beginning ; Store the output ; Print the string ; Given String ; Function Call
function printSubsequenceString ( str , k ) { let n = str . length ; let i ; let factors = new Array ( ) ; for ( let i = 2 ; i <= Math . sqrt ( k ) ; i ++ ) { while ( k % i == 0 ) { factors . push ( i ) ; k /= i ; } } if ( k > 1 ) factors . push ( k ) ; let count = new Array ( n ) . fill ( 1 ) ; let index = 0 ; while ( factors . length > 0 ) { count [ index ++ ] *= factors [ factors . length - 1 ] ; factors . pop ( ) ; if ( index == n ) index = 0 ; } let s = new String ( ) ; for ( i = 0 ; i < n ; i ++ ) { while ( count [ i ] -- > 0 ) { s += str [ i ] ; } } document . write ( s ) ; } let str = " " ; let k = 20 ; printSubsequenceString ( str , k ) ;