Valid Anagram

Problem

Given two strings s and t, return true if the two strings are anagrams of each other, otherwise return false.

An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.

Examples

Example 1:

Input: s = "racecar", t = "carrace"

Output: true

Example 2:

Input: s = "jar", t = "jam"

Output: false

Constraints

  • 1 <= s.length, t.length <= 5 * 10^4
  • s and t consist of lowercase English letters.

Solution

Count frequencies of each string, then compare for equality.

class Solution {
public:
    bool isAnagram(string s, string t) {
        std::unordered_map<char, int> counts_s;
        std::unordered_map<char, int> counts_t;
        for (const auto &c : s) {
            ++counts_s[c];
        }
        for (const auto &c : t) {
            ++counts_t[c];
        }
        return counts_s == counts_t;
    }
};