data-structures · beginner · ~15 min
Frequency counting with a fixed-size table (a hash table with perfect hashing on bytes).
Decide whether two strings are anagrams of each other.
Implement int is_anagram(const char *a, const char *b) that returns 1 if a and b contain exactly the same multiset of bytes (one is a rearrangement of the other), else 0. The comparison is case-sensitive and considers all bytes.
a, b: two NUL-terminated strings (either may be empty).
int: 1 if the strings are anagrams, 0 otherwise.
"listen", "silent" -> 1
"abc", "cab" -> 1
"aa", "a" -> 0 (length mismatch)
"", "" -> 1
"Tea", "Ate" -> 0 (case-sensitive: 'T' != 't')
"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.
a, b: two NUL-terminated strings (either may be empty).
int: 1 if the strings are anagrams, else 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.