Check whether two strings are anagram of each other

 Given two strings and b consisting of lowercase characters. The task is to check whether two given strings are an anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different.



Example 1:

Input:

a = codemummy, b = mummycode

Output: 1

Explanation: Both the string have same

characters with same frequency. So, 

both are anagrams.


Example 2:

Input:

a = allergy, b = allergic

Output: 0

Explanation: Characters in both the strings

are not same, so they are not anagrams.


method 1 :

use sorting:

sort both the string now check if the sorted strings are equal if they are equal return 1, else return 0.

c++ implementation:

bool isAnagram(string a, string b)
{
    
  sort(a.begin(),a.end());
   sort(b.begin(),b.end()); 
   
   if(a==b)
   return 1;
   else
   return 0;
}


Time Complexity: O(nlogn) 
space Complexity: O(n) 




method 2 :

take one h[] array. increment the value in h[] array for characters in string a and decrement for characters in string b. Finally, if all count values are 0, then the two strings are anagram of each other. 

c++ implementation:

bool isAnagram(string a, string b){
   int n=a.length();
   int m=b.length();
   
   if(n!=m)
   return 0;
   
  int h[26]={0};
  
  for(int i=0;i<n;i++)
  h[a[i]-'a']++;
  
  for(int i=0;i<n;i++)
  h[b[i]-'a']--;
  
  for(int i=0;i<26;i++)
 {
      if(h[i]!=0)
      return 0;
 }
  
  return 1;
}


Time Complexity: O(n) 
space Complexity: extra space for h[] array.

method 3 :

c++ implementation:

bool isAnagram(string a, string d){
 if (a.size() != d.size())
        return false;
    int count = 0;
 
    // Take sum of all characters of first String
    for (int i = 0; i < a.size(); i++) {
        count += a[i];
    }
 
    // Subtract the Value of all the characters of second
    // String
    for (int i = 0; i < d.size(); i++) {
        count -= d[i];
    }
 
    // If Count = 0 then they are anagram
    // If count > 0 or count < 0 then they are not anagram
    return (count == 0);
}


Time Complexity: O(n) 
space Complexity: O(1) 



No comments

darkmode