B. Replace Character — Why is this solution getting WA?

Revision en1, by jainyatn, 2026-05-16 14:36:02

I solved problem B "Replace Character" using frequency manipulation.

My understanding is:

  • We need to perform exactly one operation: s[i] = s[j]
  • The objective is to minimize the number of distinct permutations.
  • The statement also says we can output ANY permutation of the resulting string.

So instead of modifying the original string directly, I:

  1. Find the character with minimum frequency.
  2. Find the character with maximum frequency.
  3. Decrease the minimum frequency by 1.
  4. Increase the maximum frequency by 1.
  5. Print any permutation using the modified frequencies.

For example: abc -> cbc and since any permutation is allowed, printing bcc should also be valid.

However, this solution gets WA on hidden tests.

Code:

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

int main(){
    int t;cin>>t;

    while(t--){
        int n;
        cin>>n;

        string s;
        cin>>s;

        map<char,int>m;

        for(int i=0;i<n;i++){
            auto it = m.find(s[i]);

            if(it == m.end()){
                m[s[i]] = 1;
            }
            else{
                m[s[i]]++;
            }
        }

        char maxi = s[0];
        char mini = s[0];

        for(auto it : m){

            if(it.second >= m[maxi]){
                maxi = it.first;
            }

            if(it.second < m[mini]){
                mini = it.first;
            }
        }

        m[mini]--;
        m[maxi]++;

        for(auto it : m){
            for(int j=0;j<it.second;j++){
                cout<<it.first;
            }
        }

        cout<<endl;
    }

    return 0;
}

Can someone point out the failing case or explain what condition I am missing?

Tags combinatorics

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English jainyatn 2026-05-16 14:36:02 1839 Initial revision (published)