4/35
Part 1 of 7 · Dict of dictsLearn and do
Insert and lookup take one step per letter, however many words the trie holds
Next to a plain set of words, the trie's costs look like this.
| A set of n words | A trie of n words | |
|---|---|---|
Is tent a word? | hash all 4 letters | 4 steps down |
Does a word start with te? | look at all n words | 2 steps down |
Insert and lookup each take one dict step per letter: O(L) for a word of L letters. That's the length of the word, not the size of the dictionary.
A set lookup is O(L) as well, because hashing a new string reads all of it. So the trie doesn't win on whole words. It wins on prefix questions, which a set can only answer with a scan.
In the editor, write lookup(trie, s): a word, a prefix, or neither, in one walk. It looks up tent, ten and tex.