String which when repeated exactly K times gives a permutation of S | Java program to find a string which when repeated exactly k times gives a permutation of the given string ; Function to return a string which when repeated exactly k times gives a permutation of s ; size of string ; to frequency of each character ; get frequency of each character ; to store final answer ; check if frequency is divisible by k ; add to answer ; if frequency is not divisible by k ; Driver code ; function call
class GfG { static String K_String ( String s , int k ) { int n = s . length ( ) ; int fre [ ] = new int [ 26 ] ; for ( int i = 0 ; i < n ; i ++ ) fre [ s . charAt ( i ) - ' a ' ] ++ ; String str = " " ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( fre [ i ] % k == 0 ) { int x = fre [ i ] / k ; while ( x != 0 ) { str += ( char ) ( i + ' a ' ) ; x -- ; } } else { return " - 1" ; } } return str ; } public static void main ( String [ ] args ) { String s = " aabb " ; int k = 2 ; System . out . println ( K_String ( s , k ) ) ; } }