Tries in Python
Chapter 50: Tries
4 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
A tree of letters: how autocomplete works
A trie stores words one letter per node: the root is empty, each node's children are the letters that can come next, and a flag marks the nodes where a word ends.
Insert, search and starts-with
To search for a word or check a prefix, walk down from the root one letter at a time; if a letter is missing, the answer is no; if you reach the end, search also needs the end flag, while starts-with only needs the node.
Searching words in a grid; counting prefixes
To find many words in a grid, put them all in a trie and backtrack from every square, moving to a neighbour only if its letter is a child of the current trie node; to count words by prefix, keep on every node the number of words that pass through it.
Trie or set? Time and memory trade-offs
Use a set when you only ask whether whole words are present, and a trie when you ask about prefixes (autocomplete, counting, shortest unique starts), remembering that each trie node is a separate object with its own dict, so a trie saves letters only when many words share their starts.