data-structures · beginner · ~15 min
Frequency counting with a fixed-size table (a hash table with perfect hashing on bytes).
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.
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
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.
Two null-terminated strings.
1/0.
O(n + m). Use a 256-byte frequency table.
int is_anagram(const char *a, const char *b) { /* TODO */ return 0; }
Sorting the strings — O(n log n) when O(n) suffices. Forgetting to compare lengths first (cheaper short-circuit).
Empty strings (both empty → anagram); different lengths; identical strings.
O(n).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.