C++ code to get updated string with same 'a' and 'b' count

Suppose we have as string S with even length n. S contains only two types of characters 'a' and 'b'. We want to modify the string so that every its prefix of its length has an equal amount of letters 'a' and 'b'. To achieve that, we can perform the following operation arbitrary number of times: Select some position in his string and replace the letter on this position with the other letter. Return the updated string.

So, if the input is like S = "aabbbb", then the output will be "baabab"


To solve this, we will follow these steps −

n := size of S
for initialize i := 0, when i < n, update i := i + 2, do:
   if S[i] is same as S[i + 1], then:
      (increase ans by 1)
   S[i] := (if S[i] is same as 'a', then 'b', otherwise 'a')
return S


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
string solve(string S){
   int n = S.size(), ans = 0;
   for (int i = 0; i < n; i += 2)
      if (S[i] == S[i + 1]){
         S[i] = S[i] == 'a' ? 'b' : 'a';
   return S;
int main(){
   string S = "aabbbb";
   cout << solve(S) << endl;