data-structures · advanced · ~45 min
26-way branching pointer tree; subtree-count maintenance during insert.
Build a lowercase-ASCII trie supporting:
typedef struct trie trie_t;
trie_t *trie_create(void);
void trie_insert(trie_t *t, const char *word);
int trie_count_prefix(trie_t *t, const char *prefix);
void trie_destroy(trie_t *t);
trie_count_prefix returns the number of inserted words that start with prefix.
Tries underlie autocomplete, IP routing tables (radix tries), spell checkers, and the IPv4 BGP table compression in every internet router. Building one teaches recursive pointer structures.
Lowercase ASCII words, length <= 32. Up to 1000 words.
Count as int.
Insert and count_prefix both O(len). No malloc in count_prefix.
typedef struct trie trie_t;
trie_t *trie_create(void);
void trie_insert(trie_t *t, const char *word);
int trie_count_prefix(trie_t *t, const char *prefix);
void trie_destroy(trie_t *t);
Forgetting to bump the prefix counter on every node along the insert path; not initializing children to NULL (calloc helps); leaking allocations on destroy.
Empty prefix returns total inserted. Prefix longer than any word returns 0.
O(len) per op. Memory O(total chars * 26 pointer slots) — heavier than a hash map but cache-friendly for prefix scans.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.