Construct a string that has exactly K subsequences from given string | Java program for the above approach ; 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 ; Driver code ; Given String ; Function Call
import java . util . * ; class GFG { static void printSubsequenceString ( String str , int k ) { int n = str . length ( ) ; int i ; Vector < Integer > factors = new Vector < Integer > ( ) ; for ( i = 2 ; i <= Math . sqrt ( k ) ; i ++ ) { while ( k % i == 0 ) { factors . add ( i ) ; k /= i ; } } if ( k > 1 ) factors . add ( k ) ; int [ ] count = new int [ n ] ; Arrays . fill ( count , 1 ) ; int index = 0 ; while ( factors . size ( ) > 0 ) { count [ index ++ ] *= factors . get ( factors . size ( ) - 1 ) ; factors . remove ( factors . get ( factors . size ( ) - 1 ) ) ; if ( index == n ) index = 0 ; } String s = " " ; for ( i = 0 ; i < n ; i ++ ) { while ( count [ i ] -- > 0 ) { s += str . charAt ( i ) ; } } System . out . print ( s ) ; } public static void main ( String [ ] args ) { String str = " code " ; int k = 20 ; printSubsequenceString ( str , k ) ; } }