Trie
- Algorithms course
- Advanced
- Lesson 50/56
- 4 min
A trie supports prefix search.
Trie
A trie is a tree that stores words by their prefix. Each node represents a letter; the path from root to leaf forms a word.
It is efficient for prefix searches like autocomplete or spell check. Insert and search run in O(L) time; L is word length.
Dictionary structure
Trie nodes are represented as a dictionary. Each node holds a mapping from letter to child node. Word end is marked with '$'.
This representation lets the tree grow automatically as new letters are added. An empty trie starts with {}.
Practice init_trie function
Write init_trie(). Return an empty trie root (dictionary). Print it with print(init_trie()).
Starter code
def init_trie():
# Return empty trie rootSample solution
def init_trie():
# Return empty trie root
return {}
print(init_trie())Expected output
{}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Letter loop
for ____ in word:
for ch in word:
Explanation: ch is right.
2 What does an empty trie start with?
- []
- {} Correct answer
- 0
- ()
Explanation: An empty trie starts with {}.
3 Trie: match the terms
| Term | Meaning |
|---|---|
root |
Start |
letter |
Node |
'+' |
Word end |
dictionary |
Node structure |