Check for Palindrome after every character replacement Query in C++

C++Server Side ProgrammingProgramming

Consider we have a string and some queries in set Q. Each query contains a pair of integers i and j. and another character c. We have to replace characters at index i and j with the new character c. And tell if the string is palindrome or not. Suppose a string is like “AXCDCMP”, if we use one query like (1, 5, B), then the string will be “ABCDCBP”, then another query like (0, 6, A), then it will be “ABCDCBA”, this is palindrome.

We have to create one query using indices i, j, then replace the characters present at indices i, j in the string, with c.


 Live Demo

#include <iostream>
using namespace std;
class Query{
   int i, j;
   char c;
   Query(int i, int j, char c){
      this->i = i;
      this->j = j;
      this->c = c;
bool isPalindrome(string str){
   int n = str.length();
   for (int i = 0; i < n/2 ; i++)
   if (str[i] != str[n-1-i])
      return false;
      return true;
bool palindromeAfterQuerying(string str, Query q[], int n){
   for(int i = 0; i<n; i++){
      str[q[i].i] = q[i].c;
      str[q[i].j] = q[i].c;
         cout << str << " is Palindrome"<< endl;
         cout << str << " is not Palindrome"<< endl;
int main() {
   Query q[] = {{1, 5, 'B'}, {0, 6, 'A'}};
   int n = 2;
   string str = "AXCDCMP";
   palindromeAfterQuerying(str, q, n);


ABCDCBP is not Palindrome
ABCDCBA is Palindrome
Updated on 21-Oct-2019 14:21:21