Trie (Prefix Tree)
A trie stores words character by character. Words with the same prefix share the same path, which makes prefix search and autocomplete fast.
Inserting “cat” walks down one character per edge. Cyan nodes are already part of the trie; amber marks the current insertion path. A dashed ring means a node completes a word, so shared prefixes are stored only once.
What you are seeing
Each edge adds one character. The root represents the empty prefix.
Insertion walks down the characters, creating nodes only when a prefix does not exist yet.
A node marked as a word end completes a valid word. Its descendants are words with that prefix.
Why it matters
Tries power autocomplete, spell check, IP routing tables, and word games. They trade memory for fast prefix queries.
Complexity & details
Insert and lookup: O(L) for a word of length L. Prefix search: O(P + K) for prefix length P and K results.
Frequently asked questions
How is a trie different from a hash table?+
A hash table finds exact keys quickly but cannot enumerate prefixes. A trie naturally supports prefix queries and ordered traversal.
Why do tries use a lot of memory?+
Each character may need its own node and child map. Compressed tries and radix trees reduce this overhead by merging chains.