Tries: The Autocomplete Structure
How does a search box suggest completions the instant you type? Often, a trie โ a tree that stores words by their letters, so every word sharing a prefix shares a path. Elegant and practical.
You start typing in a search box and it instantly suggests completions - how? Often the answer is a trie (a 'prefix tree'), a structure that stores words letter by letter so that every word sharing a prefix shares a path down the tree. That arrangement makes prefix search - 'all words starting with car' - instant, which is exactly what autocomplete and spell-checkers need. It's an elegant, practical structure, and this session shows how it works.
Words stored by their letters
A trie is a tree where each edge is a letter, so a word is a path from the root spelling it out - and words with a common prefix share that prefix's path.
(root)
/ \
c d
| |
a o
/ \ \
r t g
/ \
. d # 'car', 'card', 'cat', 'dog' - shared prefixes share paths
.What a trie is great at
A trie is the specialist for prefix-based operations - things a plain list or set of words can't do quickly.
| Operation | In a trie |
|---|---|
| Does this word exist? | Walk its letters to a word-end |
| Any word with this prefix? | Walk to the prefix node |
| List all words with a prefix | Collect everything below that node |
| Autocomplete / spell-check | Exactly what it's built for |
The magic method is <b>words_with_prefix</b>: give it 'car' and it returns car, card, care - instantly, because they're all under the 'car' node. That's autocomplete. A trie trades some extra memory (all those nodes) for very fast prefix queries, which is a great deal when prefix search is what you need. It's a lovely example of a structure shaped perfectly to its problem.
The prefix specialist
- A trie stores words letter by letter, so a word is a path and shared prefixes share a path.
- Prefix search is instant - walk to the prefix node, collect everything below.
- words_with_prefix is autocomplete: 'car' -> car, card, care.
- Trades memory for fast prefix queries - perfect for autocomplete/spell-check (larztrie).
๐งฉ Do it with LarzOS
Turn this lesson into action with the exact free tools and AI workflows for the job:
๐ฏ Key takeaways
- A trie (prefix tree) stores words letter by letter, so a word is a path and words sharing a prefix share that path.
- That arrangement makes prefix search instant - walk to the prefix node and collect everything below it.
- words_with_prefix is autocomplete: give it 'car' and get car, card, care instantly.
- A trie trades extra memory for very fast prefix queries - perfect for autocomplete and spell-checkers (larztrie).
Frequently asked
Why not just store words in a list or set and search for the prefix?
You could store words in a list or set, but finding all words with a given prefix would be slow, because you'd have to check every word - whereas a trie makes prefix search fast by organising words so that a prefix leads you directly to exactly the matching words. Let's compare. With a list or set of words, to find all words starting with 'car', you'd have to examine each word in the collection and test whether it starts with 'car' - that's scanning the entire dictionary (O(number of words times prefix length)), which is slow if you have many words and are doing this on every keystroke of an autocomplete. A set makes checking whether an exact word exists fast (hashing), but it does not help with prefix queries at all - sets are organised for exact-match lookup, not prefix matching, so finding 'all words starting with car' still requires scanning everything. A trie, by contrast, organises words by their letters/prefixes, so finding all words with a prefix is fast: you walk down the tree following the prefix's letters (just a few steps, proportional to the prefix length, regardless of how many words are stored), arriving at the node representing that prefix, and then everything below that node is exactly the words with that prefix - you collect them directly without touching any non-matching words. The structure has effectively pre-grouped words by prefix, so prefix queries go straight to the relevant subset. This is a huge advantage for autocomplete: as someone types, each prefix query is fast no matter how large the dictionary, because you only ever traverse the typed prefix's path and gather its descendants, rather than scanning all words. So the trie wins specifically for prefix-based operations, which are exactly what autocomplete and spell-checking need. When would a list or set be fine instead? If you only ever check exact-word membership (does this exact word exist?), a set is simpler and fast for that - you don't need a trie. If your dictionary is tiny, scanning a list is fine too. And a trie uses more memory (many nodes) than a compact list, so if memory is very tight and prefix search isn't needed, the simpler structure is better. But the moment you need efficient prefix search - finding all words starting with something, as autocomplete requires - a trie is dramatically better than scanning a list or using a set (which doesn't support prefix search efficiently at all). The trie is a specialist: it shines precisely at the prefix queries that lists and sets handle poorly, trading extra memory for fast prefix operations. So use a set for exact membership, a list for simple storage/iteration, and a trie when prefix search (autocomplete, spell-check, 'starts with' queries) is the need. Matching the structure to the operation - prefix search wants a trie - is the point, and it's why the structure behind autocomplete is a trie rather than a plain list or set. The stack's larztrie demonstrates this directly with its words_with_prefix method, which returns matching words instantly by walking to the prefix node.
Are tries only for words, or can they store other things?
Tries are most commonly explained and used with words (sequences of letters), but the underlying idea generalises to any keys that are sequences, so tries can store more than just words - though word-based prefix search (autocomplete, spell-check) is their classic and most common application. The core concept of a trie is storing keys that are sequences by branching on each element of the sequence, so that keys sharing a common prefix share a common path. For words, the sequence elements are letters/characters, which is the familiar case. But the same structure works for other kinds of sequences: you can build a trie over sequences of digits (for things like phone number prefixes or numeric routing), over the bytes or bits of binary data, over sequences of any symbols, and even over sequences of larger units. A notable real-world example is IP routing, where specialised trie variants are used to match IP address prefixes efficiently (finding the longest matching prefix for routing packets) - the 'words' there are essentially sequences of bits. Tries and their variants also appear in areas like text processing (storing and searching many strings, as in dictionaries and spell-checkers), autocomplete and search suggestions (the classic use), IP routing tables, and some database and file-system indexing. The key requirement for a trie to make sense is that your keys are sequences with meaningful shared prefixes, so that the prefix-sharing structure provides value (fast prefix queries, space savings from shared prefixes). If your keys aren't naturally sequences with shared prefixes, a trie isn't the right fit. For most learners and most applications, the word/string case is what you'll encounter and use - building autocomplete, checking spelling, finding words by prefix - and that's what a library like larztrie focuses on (storing words for prefix search). But it's worth knowing the concept generalises: a trie is fundamentally a structure for storing sequence-keys organised by their prefixes, and 'words' are just the most common and intuitive kind of sequence-key. Understanding the word case gives you the core idea, and you can then recognise trie-like structures in other contexts (like network routing) as the same principle applied to different kinds of sequences. There are also specialised trie variants (compressed tries, radix trees, suffix trees) that optimise the basic idea for specific needs like memory efficiency or substring search - part of a rich family of prefix-based structures - but the fundamental trie you're learning, applied to words for prefix search, is the foundation and the most broadly useful version to know. So: primarily words, but the idea extends to any prefix-shareable sequences, with word-based prefix search being the classic, most common, and most practically useful application for most developers. Start with words and autocomplete (which larztrie gives you directly), and know the concept reaches further if you encounter sequence-key problems elsewhere.
Related lessons
Heaps & Priority Queues
A heap is the structure that always hands you the most important item next โ instantly. Itโฆ
Trees, Heaps & TriesChoosing the Right Structure
You now know several structures โ the real skill is picking the right one for a problem. Tโฆ
Building with the Larz StackData & Storage โ Persisting Without a Server
Most apps don't need a database server on day one. This family gives you crash-safe storagโฆ