Trie in C: solved exercise
Trie in C: solved exercise
If you searched for a solved trie in C, here is the dynamic-allocation implementation covering insertion, exact search, and prefix search. A trie (prefix tree or digital tree) stores strings by sharing characters, enabling O(m) lookups — where m is the key length — regardless of how many strings the structure holds.
Problem statement
Implement a trie for the lowercase alphabet supporting:
trie_insert(root, word): inserts a word.trie_search(root, word): returns 1 if the exact word exists.trie_prefix(root, prefix): returns 1 if any word starts with the prefix.
Insert ["house", "hard", "heart", "dog", "dot"] and test several lookups.
C solution
Expected output
Common mistakes
- Confusing exact search with prefix search:
trie_searchreturns 1 only ifend_of_wordis set at the final node;trie_prefixonly checks that the path exists. - Not using
callocor not initializing child pointers toNULL: garbage pointer values make theif (!cur->children[idx])checks incorrect. - Not handling characters outside the supported alphabet: an uppercase
'A'gives a negative index and corrupts memory. Input must be validated. - Not freeing the trie: each node is a separate
malloc/calloc; all must be freed by traversing in postorder.
Practical use
Tries are used in autocomplete (search engines, IDEs), spell checking, data compression (LZW), IP routing with CIDR prefixes, and dictionary implementations with prefix-based lookups.
Recommended next exercise
- Deque in C: solved exercise
- Binary tree in C: solved exercise
- Min-heap in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
How much memory does a trie consume?
Each node stores 26 pointers (for the a-z alphabet), consuming 26 × 8 = 208 bytes on 64-bit systems plus the end_of_word field. For small vocabularies this can be wasteful; the alternative is a compact trie (Patricia/Radix trie) that compresses paths with no branching.
Why is a trie faster than a hash table for prefix lookups?
A hash table requires searching each key individually to check whether it starts with a given prefix. A trie solves this in O(m) without traversing the whole structure: just follow the prefix path and verify that at least one descendant exists.
Can a trie be used for Unicode strings?
Yes, but the children array size must grow (or use a child→node map as a hash table or BST) to cover all possible code points. The most practical Unicode trie uses a hash map at each node.