data-structures · advanced · ~45 min
26-way branching pointer tree; subtree-count maintenance during insert.
Build a trie that can count how many stored words share a given prefix.
Implement a lowercase-ASCII trie with the following API. trie_count_prefix returns the number of inserted words that begin with 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);
'a'..'z'), length <= 32. Up to 1000 words inserted.trie_count_prefix returns an int: the number of inserted words starting with prefix.
insert "apple", "app", "apricot", "banana"
count_prefix("app") -> 2 ("apple", "app")
count_prefix("ap") -> 3 ("apple", "app", "apricot")
count_prefix("b") -> 1 ("banana")
count_prefix("z") -> 0
count_prefix("") -> 4 (every word matches the empty 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/prefixes, length <= 32; up to 1000 words.
int: number of inserted words starting with the given prefix.
root points to trie node; prefix is a null-terminated lowercase ASCII string.
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);
Dereferencing NULL child pointer when prefix path does not exist in trie.
Empty prefix, prefix not in trie, prefix matching entire word.
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.