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:
- Find the character with minimum frequency.
- Find the character with maximum frequency.
- Decrease the minimum frequency by 1.
- Increase the maximum frequency by 1.
- 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?








When I submit your code, I found this in the checker comment:
wrong answer. At most one character should differ from the original string (test case 1)You are getting this because
bccis not the solution forabc. Although it is the string that has the smallest distinct permutations, but you can't getbccfromabcin only one operation.