Skip to content
GKgkml.dev
← Problem set
#242EasyArrays & hashing

Valid Anagram

The tell: Two strings, same characters, order irrelevant.

How you get there

  1. 1An anagram is defined entirely by its character counts.
  2. 2Counter builds both in one pass each and compares in O(alphabet).
  3. 3Sorting also works at O(n log n) — mention it, then give the linear answer.

Solution

Python
from collections import Counter

def is_anagram(s: str, t: str) -> bool:
    if len(s) != len(t):
        return False
    return Counter(s) == Counter(t)
Time
O(n)
Space
O(1) over a fixed alphabet

What goes wrong

Skipping the length check is harmless here but matters when you hand-roll the counting loop.