data-structures · beginner · ~15 min

Are two strings anagrams of each other?

Frequency counting with a fixed-size table (a hash table with perfect hashing on bytes).

Challenge

Implement int is_anagram(const char *a, const char *b) returning 1 if a and b are anagrams of each other (same multiset of bytes), else 0.

For this exercise, consider all bytes (case-sensitive). Equal length is necessary for an anagram.

Examples

is_anagram("listen", "silent")   -> 1
is_anagram("abc", "cab")         -> 1
is_anagram("aa",  "a")           -> 0   // length mismatch
is_anagram("",    "")            -> 1
is_anagram("Tea", "Ate")         -> 0   // case-sensitive: T != t
is_anagram("abcd","abce")        -> 0

Why this matters

A frequency-count table (a poor-man's hash table) is the cleanest way to compare permutations of a fixed alphabet. The technique generalises directly to counting requests-per-IP, votes-per-candidate, words-per-document, and so on.

Input format

Two null-terminated strings.

Output format

1/0.

Constraints

O(n + m). Use a 256-byte frequency table.

Starter code

int is_anagram(const char *a, const char *b) { /* TODO */ return 0; }

Common mistakes

Sorting the strings — O(n log n) when O(n) suffices. Forgetting to compare lengths first (cheaper short-circuit).

Edge cases to handle

Empty strings (both empty → anagram); different lengths; identical strings.

Complexity

O(n).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.