Skip to content
Check if two strings are Anagram

Anagram in Strings

Given, two strings and we need to check if those strings form an anagram. If you are wondering what’s an Anagram? When the characters of one word are obtained from rearranging the letters/characters of another word, they are called anagrams.

Example

medical = decimal
a gentleman = elegant man
Tom Marvolo Riddle = I am Lord Voldemort

Note: Important!, Anagrams can be a single word or a group of words, but the number of characters should be the same.

Solution Approach

Here, we need to iterate through both the strings completely and count the no.of times every character occurs. We need not worry about the order or spaces in between as they don’t really matter in this case.

To track the count/occurrence of characters we can use something like a Hashmap, an array perhaps the size of [26] as there are 26 alphabets. And it’s better to convert them to either uppercase or lower case as ASCII values might cause problems.

First, create an empty array for our Hashmap h[26] = {0}

Let’s say the strings are, s1 = abc and s2 = bca.

Then, we take one string and start iterating through it, now to track the count we perform,

h[s1[0]-97]++ , okay first of all we take s1[0] which is equal to a, and the ASCII value of a is 97. On subtracting, we get 0 and h[0]++ becomes one, which means that the first alphabet has occurred one time.

And in the end, we get a[0]=1, a[1]=1, and a[2]=1.

For the second string, we perform the same. But this time, we decrement it so that the count becomes zero. Hence, if there’s an imbalance i.e the given strings are not anagrams, then the count goes negative and we can confirm that they are not anagrams.

Anagram Program

#include <iostream>
using namespace std;

int main()
{
    string a = "a gentleman";
    string b = "elegant man";

    int i, hash[26] = {0};

    for (i = 0; i < a.length(); i++)
        hash[a[i] - 97] += 1;

    for (i - 0; i < b.length(); i++)
    {
        hash[b[i] - 97] -= 1;
        if (hash[b[i] - 97] < 0)
        {
            cout << "They are not an Anagrams";
            break;
        }
    }

    if (i == b.length())
        cout << "They are Anagrams!";

    return 0;
}

Anagram – Sorting method

This problem can also be solved by sorting both the given strings and checking if all characters at every index are the same.

Conclusion

The Hashmap method simplifies our approach and the same can be used for many similar programs, What do you say?

This post is a part of my #30DaysChallenge to write a blog post every day on what I learn, Wishing you more Happiness~ Abhiram Reddy.