~/leetcode $ 242. Valid-Anagram

Question Link

Difficulty: Easy

For this question, the easiest idea is to simply keep track of the count of characters in s and then see if t has the same count of characters.

One way to do this would be to first make a dictionary/hashmap of characters in s with the character as the key and the count as the value. Then, when we go through the characters in t, we decrement the count for that character. We can remove the character from the hashmap if the count ever becomes 0. If we come across a character that does not appear in the hashmap, then t is not a valid anagram of s and we can return false.

Then, at the end, if the hashmap is empty, then t is a valid anagram of s (and so we return true). Otherwise, we return false.

As I am a cpp noobie, I do not know how to implement hashmaps in cpp so once again, some learnings:

class Solution {
public:
    bool isAnagram(string s, string t) {
        unordered_map<char, int> characterMap {};
        for (char c: s) {
            if (characterMap.contains(c)) {
                characterMap[c]++;
            } else {
                characterMap[c] = 1;
            }
        }

        for (char c: t) {
            if (characterMap.contains(c)) {
                characterMap[c]--;
                if (!characterMap[c]) {
                    characterMap.erase(c);
                }
            } else {
                return false;
            }
        }

        if (characterMap.empty()) {
            return true;
        }
        return false;
    }
};

Time Complexity: O(n)

Space Complexity: O(n)

Time Taken: 3m 25s