ANAGRAMP - Editorial

Prerequisites:- None

Problem :- Determine whether two given strings are anagrams of each other. Strings are considered anagrams if they have the same characters, in the same quantities.

Explanation :-
To compare the anagrams, we can create two dictionaries storing the frequency of characters in each string and then check the similarity between the two dictionaries. If they are similar, we can determine that the two strings are anagrams.
Steps:-
Read two strings A and B.
Create two hashmaps, dict_A and dict_B, to store the frequency of characters in each string.
Iterate through each character in string A and update dict_A with the frequency of each character.
Iterate through each character in string B and update dict_B with the frequency of each character.
Check if dict_A is equal to dict_B. If they are equal, it means both strings have the same characters with the same frequencies, making them anagrams. Print “YES”.
If dict_A is not equal to dict_B, print “NO”, indicating that the strings are not anagrams.

Solution :-
C++ Solution : -

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


bool areAnagrams(const string& str1, const string& str2) {
    if (str1.length() != str2.length()) {
        return false;
    }

    vector<int> count(26, 0);

    for (char c : str1) {
        count[c - 'a']++;
    }

    for (char c : str2) {
        count[c - 'a']--;
    }

    // If all counts are zero, then they are anagrams
    for (int i = 0; i < 26; i++) {
        if (count[i] != 0) {
            return false;
        }
    }

    return true;
}

int main() {
    int t;
    cin >> t;

    while (t--) {
        string str1, str2;
        cin >> str1 >> str2;

        if (areAnagrams(str1, str2)) {
            cout << "YES" << endl;
        } else {
            cout << "NO" << endl;
        }
    }

    return 0;
}