First string from the given array whose reverse is also present in the same array in C++


In this problem, we are given an array of string str[] of size N. Our task is to create a program for finding the first string from the given array whose reverse is also present in the same array.

Let's take an example to understand the problem,

Input: str[] = ["python", "program", "C#", "language", "#C"]
Output: C#

Solution Approach

One way to solve the problem is by directly traversing each element of the string array and checking for revere of the string in the remaining array. Return the string if the reverse is found. If the whole array is traversed and no string with the reverse present is found then return -1.

Example

Program to illustrate the working of our solution

#include<iostream>
#include<string.h>
using namespace std;
bool checkStringRev(string s1, string s2)
{
   if (s1.length() != s2.length())
      return false;
   int len = s1.length();
   for (int i = 0; i < len; i++)
      if (s1[i] != s2[len - i - 1])
          return false;
   return true;
}
string checkRevStringArr(string strArr[], int n){
   for (int i = 0; i < n - 1; i++)
      for (int j = i + 1; j < n; j++)
         if (checkStringRev(strArr[i], strArr[j]))
             return strArr[i];
   return "-1";
}
int main(){
   string strArr[] = { "python", "program", "C#", "language", "#C" };
   int n = sizeof(strArr)/sizeof(strArr[0]);
   cout<<"The string from the array whose reverse is present in the array is " <<checkRevStringArr(strArr, n);
}

Output

The string from the array whose reverse is present in the array is C#

Another method that can solve the problem in linear time i.e. in single traversal is by using a hashmap. We will be storing each word in the hashmap. If any string has its reverse present in the hashmap then the reverse string from hashmap is our result. And if the whole array does not contain any such string, return -1.

Example

Program to illustrate the working of our solution

#include<bits/stdc++.h>
using namespace std;
string checkRevStringArr(string strArr[], int length){
   map<string,bool> stringHashMap;
   for(int i = 0; i < length; i++) {
      string str = strArr[i];
      reverse(str.begin(),str.end());
      if (stringHashMap.find(str) != stringHashMap.end() and stringHashMap[str])
         return str;
      else
         stringHashMap[strArr[i]] = true;
   }
   return "-1";
}
int main(){
   string strArr[] = { "python", "program", "C#", "language", "#C" };
   int n = sizeof(strArr)/sizeof(strArr[0]);
   cout<<"The string from the array whose reverse is present in the array is "<<checkRevStringArr(strArr, n);
}

Output

The string from the array whose reverse is present in the array is C#

Updated on: 01-Feb-2022

106 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements