Print all pairs of anagrams in a given array of strings in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of strings and we have to print all pairs of anagrams of that given array.

Anagrams are strings that are formed by rearranging the character of another string. Like − hello and lolhe

Let’s take an example to understand the problem −

Input: array = {“hello”, “hrdef”, “from”, “lohel”, “morf”}.
Output: [hello, lohel] , [from , morf]

To solve this problem, we will use the nesting of loops. We need two nested loops, the outer loop will traverse over the array and select elements. The nested loop will check each of the string and check if they are anagrams or not.

Example

Let’s see the program to implement that algorithm −

 Live Demo

#include <iostream>
using namespace std;
#define NO_OF_CHARS 256
bool isAnagramString(string str1, string str2){
   int count[NO_OF_CHARS] = {0};
   int i;
   for (i = 0; str1[i] && str2[i]; i++){
      count[str1[i]]++;
      count[str2[i]]--;
   }
   if (str1[i] || str2[i])
      return false;
   for (i = 0; i < NO_OF_CHARS; i++)
      if (count[i])
         return false;
      return true;
}
void printAnagrams(string arr[], int n){
   for (int i = 0; i < n; i++)
      for (int j = i+1; j < n; j++)
         if (isAnagramString(arr[i], arr[j]))
            cout<<arr[i]<<" and "<<arr[j]<<" are anagrams.\n";
}
int main(){
   string arr[] = {"hello", "hrdef", "from", "lohel", "morf"};
   int n = sizeof(arr)/sizeof(arr[0]);
   printAnagrams(arr, n);
   return 0;
}

Output

hello and lohel are anagrams.
from and morf are anagrams.

This solution is quite easy to understand but is less efficient. So there can be some optimizations that can be made to our solutions to make it more effective. We can do it by sorting our array that contains a string. This sorted array will make anagram find easier.

raja
Published on 22-Jan-2020 09:34:31
Advertisements