Source Code
#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
#define int ll


#define lp3(i,s,n) for(int i = s;i < int(n); ++i)
#define lp(i, n) lp3(i,0,n)
#define pb push_back
#define debug(x) cout<<"[" << #x << " is: " << x << "] "<<endl;

#define file freopen("input.in","r",stdin);
#define fastIO std::ios::sync_with_stdio(false); cin.tie(0);


void solve(){
    int n, k;
    cin>>n>>k;
    string s; cin>>s;
    vector<int> freq(26, 0);
    vector<pair<int, int>> rem;
    for(char ch: s) freq[ch-'a']++;

    int remm = 0;
    lp(i, 26){
        if(freq[i]/k < freq[i]%k){
            cout<<3<<endl;
            return;
        }
        if(freq[i]%k)
            remm++;
        rem.push_back({freq[i]%k, i});
    }
    if(remm == 0){
        cout<<1<<endl;
        string kernal = "";
        lp(i, 26){
            kernal += string(freq[i]/k, (i+'a'));
        }
        string ans = "";
        lp(i, k)
            ans+=kernal;
        cout<<ans<<endl;
        return;
    }

    sort(rem.rbegin(), rem.rend());

    string pref = "";
    string next = "";
    for(auto p: rem){
        pref += string(p.first, (p.second+'a'));
        next += string(freq[p.second]/k - p.first, (p.second+'a'));
    }
    string kernal = pref+next;
    string ans = "";
    lp(i, k)
        ans+=kernal;
    cout<<2<<endl;
    cout<<ans+pref<<endl;
}

int32_t main() {  fastIO
    
    int t = 1; //cin>>t;
    while(t--){
        solve();
    }
    
    return 0;
}
Copy
Repeating Strings Logic
GNU G++17
8 ms
5.8 MB
Accepted