The Runtime Theory
easyleetcode#hash-table#string

Valid Anagram

Check if two strings are anagrams by counting character frequencies — a fixed-size counter array beats a hash map.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

ins=anagram, t=nagaram

outtrue

ins=rat, t=car

outfalse

ins=ab, t=a

outfalse

Given two strings s and t, determine whether t is an anagram of s — a rearrangement using each character exactly once. The machine must decide whether the two strings have identical character multisets.

The key insight: an anagram is a permutation, so the frequency histogram of s must equal that of t. Rather than comparing sorted versions (O(n log n)), the machine counts occurrences and compares counts. For lowercase English letters the alphabet is fixed at 26, so a plain array beats a hash map — no hashing overhead, no allocation.

Approach:

  1. Early exit: if lengths differ, they cannot be anagrams.
  2. Count each character of s into a 26-slot counter.
  3. Walk t, decrementing; if any count goes negative or any count remains nonzero, reject.
python
def is_anagram(s, t):
    if len(s) != len(t):
        return False
    counts = [0] * 26
    for ch in s:
        counts[ord(ch) - 97] += 1
    for ch in t:
        counts[ord(ch) - 97] -= 1
    return all(c == 0 for c in counts)

Time: O(n). Space: O(1), the counter is fixed-size.

Trickiest edge case: different lengths — the counts would still cancel to zero on a shared prefix, so the length check must run first, otherwise "ab" and "a" would look like anagrams of themselves.

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.