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:
- Early exit: if lengths differ, they cannot be anagrams.
- Count each character of
sinto a 26-slot counter. - Walk
t, decrementing; if any count goes negative or any count remains nonzero, reject.
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.