Trie
A trie, or prefix tree, is a tree that stores words letter by letter. Every node is one letter, and the path from the root to a node forms a word. This way words that share a prefix share its nodes.
That is why tries are helpful when you need to find words by their prefix.
Time complexity
| operation | time |
|---|---|
| insert a word of length m | |
| search a word of length m | |
| check a prefix of length m |
Implementation
Nodes
Every node should keep a map from a letter to its child and a flag that says whether a word ends at this node.
The root is a node without a letter.
Insert a word
Insert traverses the tree from the root letter by letter.
When the current node has no child for the next letter, we need to create one. The node of the last letter gets its flag set.
Search prefix or word
Search traverses the tree from the root letter by letter.
If every letter has a node, the prefix is found. To search for a word, we also need to check the flag of the last node.
Build it
Implement insert, search and starts_with in the class below.