Module 9 · Graphs and Tries · Lesson 33 of 40
Tries: trees of letters
Store words letter by letter so words with the same start share a path. Great for autocomplete.
In this lesson · about 20 minutes
- Explain how a trie stores words
- Insert words and search words and prefixes
- Say when a trie beats a set
When you type "ca" on your phone, it suggests "car", "cat" and "cake". A trie (say "try") makes this fast.
A trie is a tree where each edge is a letter. A word is a path from the root. Words with the same beginning share the same path: "car", "cart" and "cat" all share "c → a".
A trie node
class TrieNode:
def __init__(self):
self.children = {} # letter -> TrieNode
self.is_end = False # does a word end here?
Why is_end? Because "car" is a word, but it is also the start of "cart". Without the flag you couldn't tell if "car" itself was added.
Operations
- Insert: walk letter by letter, creating missing children; mark the last node
is_end = True. - Search a word: walk the letters; the word exists only if every letter is found and the last node has
is_end. - Starts with a prefix: walk the letters; if you don't fall off, some word starts with it.
Each costs O(L), where L is the length of the word, no matter how many words are stored.
Trie or set?
A set answers "is this exact word here?" in O(1) on average. But it can't answer "which words start with 'ca'?" without checking every word. A trie can. Tries power autocomplete, spell checkers and word games.
Try it · see it work
Trie: words that share a start
Type a prefix to see its path light up. Insert 'can' and 'dot' and see which nodes are shared.
Green rings mark the end of a word. The top dot is the empty root.
Exercise
Build a trie
Finish the Trie class: insert(word), search(word) (exact word) and starts_with(prefix).
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 1
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.