Meta Strings (Check if two strings can become same after a swap in one string) in C++

C++Server Side ProgrammingProgramming

In this section, we will see how to check whether two strings are meta string or not. The meta strings are those strings that are very much similar. If we swap two elements in one string, then it will be matched with other string. Suppose two strings are “HELLO” and “OELLH”, then they are meta strings.

To check whether two strings are meta string or not, we have to follow these steps.


  • If both strings are of different length, then return false

  • Else find a number of characters, that have not matched, also store the index of non-matched characters

  • If the count is greater than 2, then return false

  • Else swap these characters, then if two strings are the same, then return true, otherwise false.


 Live Demo

#include <iostream>
using namespace std;
bool areTheyMetaString(string s1, string s2) {
   int s1_len = s1.length();
   int s2_len = s2.length();
   if (s1_len != s2_len)
   return false;
   int prev = -1, curr = -1;
   int count = 0;
   for (int i=0; i<s1_len; i++) {
      if (s1[i] != s2[i]) {
         count++; // number of unmatched characters
         if (count > 2)
         return false;
         prev = curr;
         curr = i;
   return (count == 2 && s1[prev] == s2[curr] && s1[curr] == s2[prev]);
int main() {
   string s1 = "HELLO", s2 = "OELLH";
   if(areTheyMetaString(s1, s2)){
      cout << "Meta Strings";
   } else {
      cout << "Not Meta Strings";


Meta Strings
Published on 21-Oct-2019 10:45:34