Back to solutions

Valid Anagram

EasyStrings

Return true if one string is an anagram of the other, meaning they contain the same characters with the same frequencies.

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

Character counts

Time O(n)Space O(1) (fixed 26-letter table)

Anagrams have identical letter frequencies. Count letters in the first string, subtract while scanning the second, and verify every count returns to zero. Different lengths immediately fail.

#include <bits/stdc++.h>
using namespace std;

bool isAnagram(string s, string t) {
    if (s.size() != t.size()) return false;
    array<int, 26> cnt{};
    for (char c : s) cnt[c - 'a']++;
    for (char c : t) {
        if (--cnt[c - 'a'] < 0) return false;
    }
    return true;
}