Check if two strings are anagram of each other using C++


Let’s Suppose we have given two strings ‘a’ and ‘b. We have to check that the given two strings are anagram of each other or not. Two Strings are said to be anagram of each other if one string contains the same character as another.

For Example

Input-1

a= anagram
b= gnarama

Output

True

Explanation − String ‘gnarama’ has the same character as String ‘anagram’ has. Hence we return True.

Input-2

a= programmer
b= mprogretmrqp

Output

False

Explanation − String ‘b’ has more characters than the string ‘a’ and thus we can say that the length of the string is different. Thus we return False.

The approach used in the below program to solve this question is as follows

For given two strings we have the length of the string if the length of the string is different we will return False. Otherwise, if the length of the string is the same then we will check if each character of that string matches with the characters of another string and return True otherwise False.

  • Take Input two strings ‘a’ and ‘b’

  • A Boolean function checkAnagram(string a, string b) takes two strings ‘a’ and string ‘b’ and returns whether they are anagram of each other or not.

  • Find the length of the string ‘a’ and ‘b’ and check if they are equal or not. If they are not equal then return false.

  • Using C++ STL(Standard Template Library) map function, create a hash table of each character of string ‘a’ by iterating over the string ‘a’.

  • While creating a map of each character of string ‘a’ remove those characters which are present in string ‘b’.

  • Then Iterate over the map and check If there are any characters left in the hash table and return False otherwise return True.

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
bool checkAnagram(string a, string b){
   int len1= a.length();
   int len2= b.length();
   if(len1!= len2) {
      return false;
   }
   unordered_map <char,int> mp;
   for(int i=0;i<a.size();i++) {
      mp[a[i]]++;
      mp[b[i]]--;
   }
   for(auto it:mp){
      if(it.second) return false;
   }
   return true;
}
int main(){
   string a= "anagram";
   string b= "gnarama";
   cout<< checkAnagram(a,b)<<endl;
   return 0;
}

Output

If we will run the above code then it will print the output as,

1

Since Both the Input string are anagram of each other hence it returns True i.e ‘1’

Updated on: 05-Feb-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements