Print all pair of anagrams in a given array of strings

Given an array of strings. write a function that will print all anagram pairs in that array

Example

INPUT :
arr[] = {"abcde", "cdbae", "tutorial cup", "kabcd", "cup tutorial"}

OUTPUT :
Anagram pairs are : ("abcde", "cdbae"), ("tutorial cup", "cup tutorial")

Time Complexity: O(n^2*m), where n is the number of strings and m is the largest string length in the array

Algorithm

1. Simply run two loops

2. In the outer loop, pick all strings one by one

3. In the inner loop, check whether the picked string in anagram with any other string in the array

C++ Program

# include <bits/stdc++.h>
# define NO_OF_CHARS 256
using namespace std;
 
//If the given strings are anagrams, returns true else false
bool areAnagram(string s1, string s2)
{
    // Build count arrays for s1 and s2
    int s1_count[NO_OF_CHARS] = {0};
    int s2_count[NO_OF_CHARS] = {0};
    int i;
 
    // For each character in input strings, increment count in
    // the corresponding count array
    for (i = 0; s1[i] && s2[i];  i++)
    {
        s1_count[s1[i]]++;
        s2_count[s2[i]]++;
    }
 
    // If any of the two operands is non-zero, then condition becomes true.
    //If any string has more characters ie, s1 is "bfdd" and s2 is "bfd".
    //If the below condition is not present, the function says above s1 and s2 are anagrams
    //but, it is not true
    if (s1[i] || s2[i])
      return false;
 
    // Compare count arrays
    for (i = 0; i < NO_OF_CHARS; i++)
        if (s1_count[i] != s2_count[i])
            return false;
 
    return true;
}
// This function prints all anagram pairs in a given array of strings
void printAnagramPairs(string arr[], int n)
{
    cout<<"Anagram pairs are "<<endl;
    for (int i = 0; i < n; i++)
        for (int j = i+1; j < n; j++)
            if (areAnagram(arr[i], arr[j]))
                cout<<"(" << arr[i]<<"  , "<< arr[j]<<")"<< endl;
}

 

int main()
{
    string arr[] = {"abcde", "cdbae", "tutorial cup", "kabcd", "cup tutorial"};
    int n = sizeof(arr)/sizeof(arr[1]);
    printAnagramPairs(arr, n);
 
    return 0;
}
Try It

 


Next > < Prev
Scroll to Top