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

Decide whether two strings are anagrams of each other.

Task

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.

Input

a, b: two NUL-terminated strings (either may be empty).

Output

int: 1 if the strings are anagrams, 0 otherwise.

Example

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

Edge cases

  • Two empty strings are anagrams (returns 1).
  • Strings of different length can never be anagrams.

Rules

  • O(n + m): use a 256-entry byte-frequency table rather than sorting.

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

a, b: two NUL-terminated strings (either may be empty).

Output format

int: 1 if the strings are anagrams, else 0.

Constraints

a and b are null-terminated ASCII strings.

Starter code

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

Common mistakes

Indexing array with un-normalized character causing out-of-bounds access.

Edge cases to handle

Different lengths, identical strings, empty strings, strings with duplicate letters.

Complexity

O(n).

Background lessons

Up next

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