Find a palindromic string B such that given String A is a subsequence of B in C++

C++Server Side ProgrammingProgramming

Suppose we have a string A, we have to find another string B, that will be palindrome. And the given string A will be subsequence of B. The subsequence of a string is a string that can be formed by it by deleting some characters without changing the order of remaining characters. Suppose the string is “cotst”, then generated string will be “contest”. For the input of this program we have chosen A = “ab”, the generated string will be “abba”, this is palindrome.

To solve this, we will follow this approach. This is very simple, we will reverse the A, then append the reversed part after A, and form B. So B = A + reverse(A)


 Live Demo

using namespace std;
bool isPalindrome(string str) {
   string temp = str;
   reverse(str.begin(), str.end());
   return str == temp;
string formPalindromeStr(string A) {
   string B = A;
   reverse(A.begin(), A.end());
   A = A + B;
   if (isPalindrome(B))
      return B;
      return A;
string reverse(string input) {
   string temp = input;
   int left, right = 0;
   right = temp.length() - 1;
   for (left = 0; left < right; left++, right--)
   swap(temp[left], temp[right]);
   return temp;
int main(int argc, char const *argv[]) {
   string A = "Hello";
   cout << "The B is: " << formPalindromeStr(A);


The B is: olleHHello
Updated on 03-Jan-2020 09:44:13