String which when repeated exactly K times gives a permutation of S | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string K_String ( string s , int k ) { int n = s . size ( ) ; int fre [ 26 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) fre [ s [ i ] - ' a ' ] ++ ; string str = " " ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( fre [ i ] % k == 0 ) { int x = fre [ i ] / k ; while ( x -- ) { str += ( char ) ( i + ' a ' ) ; } } else { return " - 1" ; } } return str ; } int main ( ) { string s = " aabb " ; int k = 2 ; cout << K_String ( s , k ) ; return 0 ; }