# Anagram words
An anagram is a word made by using letters of another word in a different order.
Example: later & alert , earth & heart.
For two words to be anagrams they should have:
- Same number of letters
- made up of same letters, which may be arranged in different order.
Steps:
- Check if both words have same length, if not they cannot be anagrams.
- If yes, Sort both words and compare them letter by letter.
- If all letters are same they both are anagrams.
# Source Code - C++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool isAnagram (string A, string B){
int n1, n2, i;
n1 = A.length();
n2 = B.length();
if(n1 != n2)
return false;
sort(A.begin(), A.end());
sort(B.begin(), B.end());
for(i =0 ; i<n1 ; i++)
{
if( A[i] != B[i] )
return false;
}
return true;
}
int main()
{
string A,B;
bool ans;
cout<<"Enter first word\n";
cin>>A;
cout<<"Enter second word\n";
cin>>B;
ans = isAnagram(A,B);
if(ans==1)
cout<<"Words are anagrams\n";
else
cout<<"Words are not anagrams";
return 0;
}
Time Complexity : O(nlogn)