Check Anagram - C++ Solution

1. Introduction

In this blog post, we delve into the intriguing world of anagrams. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Identifying anagrams has applications in various fields, including linguistics, cryptography, and word games.

Problem

Given two strings, the objective is to determine if they are anagrams of each other. This means we need to check if one string can be rearranged to form the other, using all the original letters exactly once.

2. Solution Steps

1. Check if both strings are of the same length. If not, they cannot be anagrams.

2. Create a frequency table to count the occurrences of each character in the first string.

3. Decrease the frequency of each character found in the second string.

4. If the frequency table has all zeros, the strings are anagrams; otherwise, they are not.

3. Code Program

#include <iostream>
#include <vector>
#include <string>
using namespace std;

// Function to check if two strings are anagrams
bool areAnagrams(const string& X, const string& Y) {
    if (X.length() != Y.length()) return false; // Strings of different lengths can't be anagrams

    vector<int> frequency(256, 0); // ASCII character frequency table

    // Increase the frequency based on characters of X
    for (char ch : X) {
        frequency[ch]++;
    }

    // Decrease the frequency based on characters of Y
    for (char ch : Y) {
        frequency[ch]--;
        if (frequency[ch] < 0) {
            return false; // Character in Y not found in X or mismatch in frequency
        }
    }

    return true; // Strings are anagrams
}

int main() {
    string X = "silent", Y = "listen";
    cout << "Are \"" << X << "\" and \"" << Y << "\" anagrams? " << (areAnagrams(X, Y) ? "true" : "false") << endl;
    return 0;
}

Output:

Are "silent" and "listen" anagrams? true

Explanation:

The function areAnagrams checks if two strings are anagrams of each other. It first verifies if the strings are of equal length. 

Then, it creates a frequency table for ASCII characters, incrementing counts based on the characters of the first string and decrementing based on the second. If the frequency table is balanced (all zeros), it indicates that the strings are anagrams. 

For example, "silent" and "listen" are anagrams, as rearranging "silent" forms "listen" and vice versa.


Comments