Source Code
#include <bits/stdc++.h>
using namespace std;
#define oo 1000000010
#define mod 1000000007
const int N = 1000010;

int n , k;

char s[N];

int frq[26];

int a[N] , b[N];


int main(){
	scanf("%d%d",&n,&k);
	scanf("%s",s);
	for(int i = 0 ;i < n;i++){
		frq[s[i] - 'a']++;
	}
	int type = 1;
	for(int i = 0 ;i < 26;i++){
		a[i] = frq[i] / k;
		b[i] = frq[i] % k;
		if(b[i] != 0)
			type = 2;
		if(b[i] > a[i]){
			type = 3;
			break;
		}
	}
	cout << type << endl;
	if(type != 3){
		string s = "";
		string pref = "";
		for(int i = 0 ;i < 26;i++){
			while(b[i] > 0){
				s += i + 'a';
				b[i]--;
				a[i]--;
				pref += i + 'a';
			}
		}
		for(int i = 0 ;i < 26;i++){
			while(a[i] > 0){
				a[i]--;
				s += i + 'a';
			}
		}
		for(int i = 0 ;i < k;i++){
			printf("%s",s.c_str());
		}
		puts(pref.c_str());
	}

	return 0;
}
Copy
Repeating Strings Kilani
GNU G++17
10 ms
3.1 MB
Accepted