Break a Palindrome in C++

C++Server Side ProgrammingProgramming

Suppose we have a palindromic string palindrome, we have to replace exactly one character by any lowercase English letter so that the string becomes the lexicographically smallest possible string that isn't a palindrome. Now after doing so, we have to find the final string. If there is no way to do so, then return the empty string. So if the input is like “abccba”, then the output will be “aaccba”.

To solve this, we will follow these steps −

  • changed := false

  • if the size of a string is 1, then return a blank string

  • i := 0 and j := length of s – 1

  • leftA := True and rightA := True

  •  while i < j −

    • if s[i] is not ‘a’, then set s[i] as ‘a’ and return s

    • increase i by 1 and decrease j by 1

  • s[size of s - 1] := ‘b’

  • return s

Example (C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   string breakPalindrome(string s) {
      bool changed = false;
      if(s.size() == 1)return "";
      int i = 0, j = s.size() - 1;
      bool leftA = true;
      bool rightA= true;
      while(i < j){
         if(s[i] != 'a'){
            s[i] = 'a';
            return s;
      s[s.size() - 1] = 'b';
      return s;
   Solution ob;
   cout << (ob.breakPalindrome("abccba"));




Published on 31-Mar-2020 10:58:31