Part 17 / Topic 15 of 20
Tries
A trie (prefix tree) stores words as paths of letters from a shared root, so every word starting with "ra" walks the same first two nodes. Looking a word up costs O(length of the word) β no matter whether the trie holds a hundred words or a million. That is the structure behind autocomplete, spell-check and "did you mean". Think of a telephone directory tree: one branch per next letter. To find everyone called "Rajβ¦", walk r β a β j once, and every name below that point is a match.
| Operation | Cost | Compare: a plain list of words |
|---|---|---|
| insert / exact lookup | O(word length) | O(total words) scan |
| "any word with this prefix?" | O(prefix length) | O(total words Γ prefix) |
| collect all matches for a prefix | O(size of the matching subtree) | O(total words) |
class TrieNode:
def __init__(self):
self.children = {} # letter -> TrieNode
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for letter in word:
node = node.children.setdefault(letter, TrieNode())
node.is_word = True
is_word matters: after inserting "raj" and "rajesh", the node at j is a finished word AND has children. Autocomplete walks to the prefix's node, then collects every finished word beneath it:
contains 'raj': True
contains 'ra': False (a prefix, not a stored name)
autocomplete 'ra': ['raj', 'rajesh', 'rani', 'ravi']
autocomplete 'z': []
Real-world example: a phone's contact search suggesting names as you type is a trie walk per keystroke β each new letter just steps one node deeper instead of re-scanning every contact.
β οΈ Forgetting the
is_wordflag makes every prefix look like a stored word ("ra"would match). And a trie of long strings over a big alphabet eats memory fast β for a plain "is this exact word present?" check with no prefix queries, asetis simpler and cheaper.
Practice: build insert/contains/starts_with from scratch; autocomplete (collect all words under a prefix); word search with wildcards or over a letter grid.
Practice on LeetCode - start here: Implement Trie (Prefix Tree)
Show the full practice list (7 more problems)
Core practice - gentler first:
| Problem | Difficulty |
|---|---|
| Design Add and Search Words Data Structure | Medium |
| Replace Words | Medium |
| Longest Word in Dictionary | Medium |
| Map Sum Pairs | Medium |
| Search Suggestions System | Medium |
Stretch - tougher; come back once the core feels comfortable:
| Problem | Difficulty |
|---|---|
| Word Search II | Hard |
| Stream of Characters | Hard |
Full program: examples/15_tries.py.
Exercise 15: Tries β contact autocomplete
Scenario: A phone's contact search must suggest every saved name starting with whatever has been typed so far.
What to do: Build a Trie class with insert(word) and autocomplete(prefix) (walk to the prefix's node, then collect every finished word beneath it, sorted; an unknown prefix returns []). Insert the names below and print the completions for "ra", "raj" and "z".
Starting data:
NAMES = ["ravi", "rani", "raj", "rajesh", "asha", "arun"]
Sample output:
'ra' -> ['raj', 'rajesh', 'rani', 'ravi']
'raj' -> ['raj', 'rajesh']
'z' -> []
Show the solution to Exercise 15
"""Exercise 15: Tries - contact autocomplete.
Insert each name letter by letter; autocomplete walks to the prefix's
node and collects every finished word underneath it.
Run: python ex15.py (macOS/Linux: python3 ex15.py)
"""
NAMES = ["ravi", "rani", "raj", "rajesh", "asha", "arun"]
class TrieNode:
def __init__(self) -> None:
self.children: dict[str, TrieNode] = {}
self.is_word = False
class Trie:
def __init__(self) -> None:
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for letter in word:
node = node.children.setdefault(letter, TrieNode())
node.is_word = True
def autocomplete(self, prefix: str) -> list[str]:
node = self.root
for letter in prefix:
node = node.children.get(letter)
if node is None:
return []
found: list[str] = []
def collect(node: TrieNode, word: str) -> None:
if node.is_word:
found.append(word)
for letter, child in node.children.items():
collect(child, word + letter)
collect(node, prefix)
return sorted(found)
def main() -> None:
contacts = Trie()
for name in NAMES:
contacts.insert(name)
for prefix in ["ra", "raj", "z"]:
print(f"{prefix!r} -> {contacts.autocomplete(prefix)}")
if __name__ == "__main__":
main()