Store words letter by letter so words that start the same share a path, insert, search and ask about a prefix, see why the end mark matters, and build your own trie.
You type ca into a search box, and it offers car, cart and cat at once. It did not read through a million words to find them. It stood on a spot that means "words that start with ca", and looked below it.
A list of words cannot do that cheaply, because each word is a separate string. You need a structure where words that start the same share the same start.
Picture a dictionary with thumb tabs. The tab c holds every word that starts with c. Inside it, a second tab a holds every word that starts with ca. Each tab narrows the search by one letter.
A trie is that idea made exact. Every letter you read takes you one step further into the dictionary.
A trie is a dictionary with thumb tabs: each letter is a tab that narrows the search. Words that start the same share the same tabs.
A trie (say "try", from retrieval) is a tree where each edge is one letter. Each node is a prefix: the letters on the path from the root to it. The root is the empty prefix.
Words that start the same share the same path. The words car and cat share the nodes for c and ca, and then split into r and t.
A node can be marked as an end. That mark says that a whole word was stored here. The node for ca has no mark if only car and cat were inserted, so ca is a start, and not a word.
A trie is a tree, like the one in the last modules. The difference is that the information is on the edges, and a node has up to one child for each letter.
Step by step: One word list, stored as a trie. The animated player loads in your browser.
Predict what happens
Q A trie holds the words car and cat. Which nodes do the two words share?
Answer: B
A node is a prefix. Both words start with c and ca, so those two nodes are used by both. The words split at the third letter.
A trie has three main operations. All three do one thing: walk down the letters of a word from the root.
To insert a word, start at the root. For each letter, follow the edge with that letter. If the edge does not exist, make a new node and an edge to it. After the last letter, mark the node as an end.
If the word was already stored, every edge exists, and nothing new is made. If the word is the start of a stored word, the nodes exist, and only the end mark is new.
Trace it on an empty trie. Inserting car finds no edges, so it makes three nodes, c, ca and car, and marks car. Inserting cat follows c and ca, and makes only one node, cat. Inserting ca follows two edges, makes nothing, and only marks ca as an end.
To insert a word, walk its letters from the root. Follow an edge that exists, or make a node. Then mark the last node as an end.
Step by step: Insert cart. The animated player loads in your browser.
To search for a word, walk its letters. If an edge is missing, the answer is no. If the walk works, look at the last node. The answer is yes only if the node is marked as an end.
That second check matters. If car is stored, the walk for ca works, but ca is not a word.
Search walks the letters, and answers yes only if every edge exists and the last node is marked as a word end.
Step by step: Is ca a stored word?. The animated player loads in your browser.
Exercise · Predict the output: How far does each walk get?. The words car, cart, cat and dog are stored. For each text, the code walks its letters down the trie from the root and stops at the first missing edge. It prints how many letters were matched. What does it print for cart, cats, cow and dot?
words = ["car", "cart", "cat", "dog"]
child = [{}]
for word in words:
node = 0
for ch in word:
if ch not in child[node]:
child.append({})
child[node][ch] = len(child) - 1
node = child[node][ch]
for text in ["cart", "cats", "cow", "dot"]:
node = 0
matched = 0
for ch in text:
if ch not in child[node]:
break
node = child[node][ch]
matched += 1
print(matched, end=" ")
print()Predict what happens
Q The words car and cat are stored. You search for ca. What is the answer?
Answer: B
Search needs every edge and the end mark. The node for ca has both edges but no end mark, so ca is only a start.
To ask whether any word starts with some letters, walk the letters. If every edge exists, the answer is yes. The end mark does not matter, because everything below the node starts with the prefix.
This is the question a hash set cannot answer fast. A trie answers it in the length of the prefix.
Starts with walks the letters of the prefix. If every edge exists, some word starts with it, and the end mark does not matter.
Step by step: Does any word start with ca?. The animated player loads in your browser.
Exercise · Find the bug: The prefix that is not a word. This builds a trie from the words, then says whether any stored word starts with the prefix. It answers False for some prefixes that do start a word. Which line is wrong?
def starts_with(words, prefix):
child = [{}]
ends = [False]
for word in words:
node = 0
for ch in word:
if ch not in child[node]:
child.append({})
ends.append(False)
child[node][ch] = len(child) - 1
node = child[node][ch]
ends[node] = True
node = 0
for ch in prefix:
if ch not in child[node]:
return False
node = child[node][ch]
return ends[node]Predict what happens
Q A trie holds a million words. You ask whether any word starts with the 3 letters "zeb". About how many letters does the walk read?
Answer: B
The walk reads only the letters of the prefix. It stops early if an edge is missing. The number of stored words does not change it.
A node needs a way to find its children. There are two usual choices.
For lowercase words, either works. For a large alphabet, such as all of Unicode, a map is the practical choice.
A trie makes one node for each different prefix. Words that share a start share nodes, so six nodes can hold nine letters.
Exercise · Break it: The search box that cares about capitals. A search box should find a stored word whatever capitals the user types. This function lowercases every word as it inserts it into the trie, then looks the query up. Find an input where it gives the wrong answer.
def contains(words, query):
child = [{}]
ends = [False]
for word in words:
node = 0
for ch in word.lower():
if ch not in child[node]:
child.append({})
ends.append(False)
child[node][ch] = len(child) - 1
node = child[node][ch]
ends[node] = True
node = 0
for ch in query:
if ch not in child[node]:
return False
node = child[node][ch]
return ends[node]Predict what happens
Q You insert car, cat, cart and cow. How many nodes does the trie have, not counting the root?
Answer: C
A node is a different prefix. The shared c is one node, ca is shared by car, cat and cart, and car is shared by car and cart. That leaves c, ca, car, cat, cart, co and cow.
Take a word of length m, and n words stored in all. Here is each operation side by side.
| Operation | Trie | Hash set of words | Sorted list | What sets the cost |
|---|---|---|---|---|
| Insert a word | O(m): one step for each letter | O(m): hash the word | O(n): shift entries to keep the order | The letters of the word, or the shifting |
| Search for a whole word | O(m) | O(m) on average | O(m log n): binary search | Comparing letters on the way |
| Does any word start with a prefix | O(length of the prefix) | O(n × m): test every word | O(p log n): binary search | Whether the words are grouped by start |
| Delete a word | O(m): unmark, and remove the unused nodes | O(m) | O(n): shift entries | The letters of the word |
| List the words under a prefix | O(p + size of the answer) | O(n × m): test every word | O(p log n + size of the answer) | Where the words are kept together |
| Memory | One node for each different prefix, at most the total letters, but each node also holds a map or 26 slots | O(total letters) | O(total letters) | Shared starts against the cost of each node |
A trie wins when you ask about starts. A hash set wins when you only ever ask about whole words and memory is tight. A trie saves letters only when many words share starts. Each node costs far more than one letter, so in practice a trie often uses more memory than a set.
Now drive a trie yourself. Type a word, then insert it, search for it, or ask whether any word starts with it. Each operation runs letter by letter, with the node being looked at lit, and a counter of letters read.
Try these six, in order:
cart. Watch the shared nodes get followed, and the new ones get made.car, and then for ca. Compare the two answers and see why.ca, then cab. Count the letters read.ca. Which nodes are new?The sandbox: build a list and run its operations step by step. It loads in your browser.
Now write the structure yourself. The lab gives you a Trie class for the index behind a search box. You write four methods: insert, search, starts_with and node_count.
Three things to take care over:
insert makes a node for each letter that has no edge yet, and marks the last node as an end. Inserting a word twice changes nothing.search is true only for a word that was inserted. A start of a stored word gives false.starts_with is true when every edge of the prefix exists, whether or not the prefix is a word. node_count does not count the root.Each test creates a new, empty trie, calls your methods in order and compares every value they return. When a test fails, the result names the exact call that went wrong, the value it returned and the value it should return.
Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Use a trie when the questions are about the start of a word. Examples are autocomplete, a spell checker, a contact search and a word game. A router that matches the longest start of an address is another.
It also fits when many words share long starts, because the shared part is stored once.
If you only ever ask whether a whole word is stored, a hash set is simpler and smaller. If the words are fixed and you ask about starts, a sorted list and binary search can do it with less memory.
A trie with an array of slots on each node wastes memory for a large alphabet, or for words that rarely share a start.
If a node has no end mark, a word and the start of a longer word look the same. Then a search for ca says yes after only car was inserted.
return node != -1 # wrong: the walk works for a start too
return node != -1 and ends[node] # right: the word must end hereWithout the end mark, a stored word and the start of a longer word look the same. Search would say yes for a start that was never inserted.
A search must only read the trie. If it makes a node for a missing letter, it changes what is stored, and later answers become wrong.
if ch not in child[node]:
child[node][ch] = new_node() # wrong inside a search: it adds a node
return False # right: stop at the missing edgeAn array of 26 slots on each node is fast, but a million nodes then hold 26 million slots, almost all empty. A map on each node keeps only the letters that exist.
child = [[-1] * 26 for _ in range(nodes)] # 26 slots on every node
child = [{} for _ in range(nodes)] # only the letters that existCar and car are different paths in a trie. If the search box ignores case, make every word lowercase before you insert or search, and trim spaces. Decide the rule once and use it everywhere.
word = word.strip().lower() # one rule, applied to every wordKeeping the whole prefix as a string on each node makes the memory grow with the square of the word length. The path already spells the prefix. Store only the letter, or nothing, on the node.
node.prefix = word[:i] # copies i letters for every node
node.prefix = None # the path from the root already spells itExplain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · What a node is
Q In a trie, what does a node stand for?
Answer: C
A node stands for the prefix spelled by the path from the root. The letter itself sits on the edge that leads to the node.
Checkpoint · Sharing
Q A trie holds car and cart. How many nodes do they use, not counting the root?
Answer: B
The word car uses c, ca and car. Cart reuses all three and adds one node for t. That makes 4.
Checkpoint · Insert cost
Q You insert a word of 6 letters into a trie that holds 100,000 words. About how many steps does it take?
Answer: B
Insert walks one edge for each letter, making a node when an edge is missing. The number of stored words does not change the cost.
Checkpoint · The end mark
Q Only the word car is stored. What does search ca answer, and why?
Answer: C
The walk for ca works, but search also needs the end mark. No word was inserted that ends at ca.
Checkpoint · Starts with
Q Only the word car is stored. What does starts with ca answer?
Answer: B
Starts with needs only the walk to work. The end mark does not matter for a prefix.
Checkpoint · Why a trie
Q Which question is a trie much faster at than a hash set of words?
Answer: B
A hash set finds a whole word fast but must test every word for a prefix. A trie answers a prefix by walking only its letters.
Checkpoint · Memory
Q A trie gives each node an array of 26 slots, and 1,000,000 nodes are made. About how many slots are reserved?
Answer: B
Every node reserves 26 slots, whether it needs them or not: 26 million. A map on each node keeps only the letters that exist.
Checkpoint · Delete
Q You delete the word cat from a trie that holds car and cat. What must you do?
Answer: B
Unmark the end, then remove nodes from the bottom while they have no children and are not an end. The nodes c and a are still used by car.
Checkpoint · A mistake
Q A search makes a new node when an edge is missing, and then says no. What goes wrong?
Answer: B
A search must only read. A node made by a search would later look like a stored start, so starts with could answer yes for something never inserted.
Checkpoint · Choosing
Q You only ever ask whether a whole word is stored, and memory is tight. What is the better choice?
Answer: B
For whole-word questions, a hash set is simpler and smaller. A trie pays off when you ask about starts.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.