Tries · Stage 1 of 3
Prefix Tree Insertion & Lookup
Walk one character edge per level to match words and prefixes in O(L) time
Foundations
A trie, or prefix tree, stores strings by their characters. Each node holds a map from a character to a child node, so every edge spells one character and a path from the root spells a prefix. A flag on a node, isEnd, marks where an inserted word ends; the code here stores it as a "$" key. Words that share a prefix share its nodes, so a common start is stored once.
Insert walks the word from the root, creating any missing child, and sets isEnd on the last node. Lookup walks the same way and fails at the first missing edge. A word is present only if the walk ends on an isEnd node, while a prefix only needs the walk to succeed. Each step is one map lookup, so both cost O(L) for a word of length L, however many words are stored.
Insert words = ["to", "tea", "ten", "inn"]: t is shared by three words, and e by tea and ten, so the trie has 8 nodes besides the root instead of 11 letters. Looking up ten walks t, e, n and ends on an isEnd node: found. Looking up te stops on e, which has no isEnd: a prefix, not a word.
isEnd set. Looking up ten followed 3 edges to a marked node; te stops on e, a prefix but not a word.- Open lesson
Hashing
Each trie node is a dict from a character to a child. That lesson covers dict lookups.
Case Scenario
The problem
Implement Trie (Prefix Tree)
Implement a trie with insert, search (whole word), and startsWith (prefix). Tests call trie(ops, args).
- Input
- operations = ["Trie", "insert", "search", "search", "startsWith", "insert", "search"], arguments = [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
- Output
- [None, None, True, False, True, None, True]
Implement Trie (Prefix Tree) asks for exactly these operations: insert, search for a whole word, and startsWith for a prefix. In the example, after insert("apple"), search("app") is False because the second p has no end mark, while startsWith("app") is True; once insert("app") sets that mark, search("app") becomes True.
The direct approach keeps the words in a list. Inserting is instant, but search and startsWith compare the query with every stored word: O(n · L) for n words. Autocomplete over a million words would scan a million entries per keystroke, though a query of a few letters can only match words that start with those letters.
Pro
The rest of this is on Pro
The idea above is free. The walkthrough, the cost, and the practice are on Pro.