~/Coding Clutch/article.md
DSA

How Autocomplete Works: Trie Data Structure Explained

August 14, 2026 · 15 min read

How Autocomplete Works: The Trie Data Structure Behind Search Suggestions

You type ca into a search box and suggestions appear before you reach the third key. This post shows how autocomplete works under the hood: you’ll build a trie (prefix tree) in Python and C++, trace it by hand, and then fix its biggest weakness, which is ranking suggestions, not finding them. You’ll also see where a plain sorted array beats a trie, and what Google and Elasticsearch say about their own approaches. If you want the cost model behind the complexity claims, read our complete guide to time and space complexity first.


Phase 1: The Problem

You run a store with 1,000,000 past search queries. Every keystroke should show the five best completions of what the user has typed so far.

The brute-force version is a filter:

def suggest_naive(queries: list[str], prefix: str) -> list[str]:
    return [q for q in queries if q.startswith(prefix)]

This is O(N · |p|) per keystroke, where N is the number of queries and |p| is the prefix length. With a million queries, a user typing a 10-character search triggers ten full scans. It also returns every match, unranked, so for the prefix a you’d build a list of tens of thousands of strings just to show five.

Two problems are hiding in here. The first is finding everything that starts with a prefix quickly. The second, which tutorials rarely mention, is ranking those matches so you can stop early. A trie solves the first problem cleanly. The rest of this post is about how far it gets you on the second.


Phase 2: The Pattern

The mental model: a road network with shared trunk roads

Think of every word as a route from a central station (the root). Words that start the same way share the same road until they fork. Each junction is a character, and each word ends at a junction marked as a destination.

To autocomplete, you drive the road for the prefix the user typed. If the road doesn’t exist, there are no completions. If it does, every destination reachable from where you’re standing is a valid completion.

(root)
├── c
│   └── a
│       ├── r *          car
│       │   ├── d *      card
│       │   └── e *      care
│       └── t *          cat
└── d
    └── o
        └── g *          dog

* marks a node where a word ends. Five words with 17 total characters occupy 9 nodes, because car, card, care, and cat share the c → a trunk.

When to recognize the pattern

Look for these phrases in a problem statement:

  • “starts with” / “prefix” / “common prefix”
  • “autocomplete,” “search suggestions,” “type-ahead”
  • A dictionary of words queried many times
  • “Replace words with their shortest root”
  • “Add and search words” with wildcards
  • Maximize XOR of two numbers (a trie over bits)
  • Word search on a board with many target words

What most tutorials get wrong

Most trie tutorials stop at insert, search, and startsWith. That solves “does this prefix exist?” but not autocomplete, which is “give me the best five completions.”

Walk the subtree under the prefix a in a large dictionary and you visit a huge fraction of all words, then sort them. That’s slow exactly when users type their first character, which is when latency matters most. The real design work is ranking: precomputing the top-k at each node, or building a structure that returns results in rank order.

Also, a trie isn’t automatically the best tool for prefix lookup. A sorted array with binary search gives you the same prefix range with much less memory (Phase 5). The trie earns its place when you need incremental traversal, per-node metadata, or the variants below.


Phase 3: Step-by-Step Walkthrough

Building the trie

Insert four words: car, card, care, cat.

WordPath walkedNew nodes createdTotal nodes
carc → a → rc, a, r3
cardc → a → r → dd4
carec → a → r → ee5
catc → a → tt6

Fourteen characters went in and six nodes came out. The saving grows when many strings share long prefixes, which is common for search queries.

Querying the prefix ca

Assign counts as popularity: car 40, card 25, care 30, cat 90. The query has two phases. First, walk the prefix: root → c → a. Second, collect every word below that node with an explicit stack (a depth-first traversal).

StepPopPathWord ends here?Push
1node acano(r, car), (t, cat)
2node tcatyes (90)none
3node rcaryes (40)(d, card), (e, care)
4node ecareyes (30)none
5node dcardyes (25)none

Collected: cat, car, care, card. Sorting by count descending gives cat (90), car (40), care (30), card (25), so the top three are cat, car, care.

Step E is the expensive one. Phase 4 shows how to make it constant-time with respect to the subtree size.


Phase 4: Code Templates

Python: the basic trie

class TrieNode:
    __slots__ = ("children", "count")

    def __init__(self) -> None:
        self.children: dict[str, "TrieNode"] = {}
        self.count = 0          # > 0 means a word ends here (its popularity)


class Trie:
    def __init__(self) -> None:
        self.root = TrieNode()

    def insert(self, word: str, count: int = 1) -> None:
        node = self.root
        for ch in word:
            node = node.children.setdefault(ch, TrieNode())
        node.count += count

    def _find(self, prefix: str) -> TrieNode | None:
        node = self.root
        for ch in prefix:
            node = node.children.get(ch)
            if node is None:
                return None
        return node

    def complete(self, prefix: str, k: int = 5) -> list[str]:
        start = self._find(prefix)
        if start is None:
            return []
        found: list[tuple[str, int]] = []
        stack = [(start, prefix)]
        while stack:
            node, path = stack.pop()
            if node.count > 0:
                found.append((path, node.count))
            for ch, child in node.children.items():
                stack.append((child, path + ch))
        found.sort(key=lambda t: (-t[1], t[0]))   # popularity desc, then alphabetical
        return [w for w, _ in found[:k]]


t = Trie()
for w, c in [("car", 40), ("card", 25), ("care", 30), ("cat", 90)]:
    t.insert(w, c)

print(t.complete("ca", 3))    # ['cat', 'car', 'care']
print(t.complete("car"))      # ['car', 'care', 'card']
print(t.complete("cx"))       # []

Requires Python 3.10+ for the X | None annotation syntax. There are no dependencies.

What problem it solves: prefix lookup in O(|p|) steps, independent of how many words are stored.

Key parts: a dict of children per node, a terminal marker (count > 0), a prefix walk, and an iterative DFS (no recursion limit to worry about).

Production notes:

  • Time: insert is O(L). A prefix walk is O(|p|). Collecting is O(S) for a subtree of S nodes, plus O(M log M) to sort M matches.
  • The weakness is that S is huge for short prefixes. The one-letter prefix visits a large part of the structure.
  • Memory: each node holds a dict, which is heavy in Python. For very large vocabularies, the per-node overhead usually dominates the character data.

Python: top-k cached at every node

The fix for slow short prefixes is to precompute the answer. Each node stores its own top-k list, so a query is just a prefix walk and a read.

class TopKNode:
    __slots__ = ("children", "top")

    def __init__(self) -> None:
        self.children: dict[str, "TopKNode"] = {}
        self.top: list[tuple[int, str]] = []     # sorted [(-count, word)], len <= k


class TopKTrie:
    def __init__(self, k: int = 5) -> None:
        self.root = TopKNode()
        self.k = k

    def add(self, word: str, count: int) -> None:
        """Add each distinct word once; aggregate counts before calling."""
        entry = (-count, word)
        node = self.root
        self._push(node, entry)
        for ch in word:
            node = node.children.setdefault(ch, TopKNode())
            self._push(node, entry)

    def _push(self, node: TopKNode, entry: tuple[int, str]) -> None:
        node.top.append(entry)
        node.top.sort()
        del node.top[self.k:]

    def suggest(self, prefix: str) -> list[str]:
        node = self.root
        for ch in prefix:
            node = node.children.get(ch)
            if node is None:
                return []
        return [word for _, word in node.top]


tk = TopKTrie(k=3)
for w, c in [("iphone 15", 900), ("iphone charger", 700), ("iphone case", 650),
             ("ipad", 500), ("ipod", 100), ("ice cream", 300)]:
    tk.add(w, c)

print(tk.suggest("ip"))    # ['iphone 15', 'iphone charger', 'iphone case']
print(tk.suggest("ic"))    # ['ice cream']
print(tk.suggest("x"))     # []

The counts above are made-up numbers for illustration.

What problem it solves: query time no longer depends on how many words sit under the prefix.

Key parts: a small sorted list on every node, updated as each word is added along its path.

Production notes:

  • Query time is O(|p|) plus reading k items. Build time is O(total characters × k log k) with this simple sort, and it can be made cheaper with a heap.
  • The trade-off is memory: every node now holds up to k entries (these can be pointers or IDs instead of full strings).
  • Updates are the pain point. When a word’s popularity changes, every node on its path may need its list recomputed. In practice, ranking data is often rebuilt in batches rather than updated on every search. That’s my inference from the structure’s cost, not a claim about any specific company.

C++: array-based trie (lowercase a to z)

#include <array>
#include <memory>
#include <string>

struct Node {
    std::array<std::unique_ptr<Node>, 26> next{};
    bool end = false;
};

class Trie {
    Node root_;

    const Node* find(const std::string& s) const {          // O(|s|)
        const Node* cur = &root_;
        for (char c : s) {
            const auto& nxt = cur->next[c - 'a'];
            if (!nxt) return nullptr;
            cur = nxt.get();
        }
        return cur;
    }

public:
    void insert(const std::string& w) {                     // O(|w|)
        Node* cur = &root_;
        for (char c : w) {
            auto& nxt = cur->next[c - 'a'];
            if (!nxt) nxt = std::make_unique<Node>();
            cur = nxt.get();
        }
        cur->end = true;
    }
    bool contains(const std::string& w) const {             // O(|w|)
        const Node* n = find(w);
        return n && n->end;
    }
    bool startsWith(const std::string& p) const {           // O(|p|)
        return find(p) != nullptr;
    }
};

What problem it solves: constant-time child lookup with no hashing, and automatic cleanup through unique_ptr.

Key parts: a fixed 26-slot child array, an end flag, and a shared find helper.

Production notes:

  • Each node carries 26 pointers, roughly 200+ bytes on a 64-bit machine, even if it has one child. For sparse tries or large alphabets (Unicode), use a map or a compressed trie.
  • Input must be lowercase a to z, or the index c - 'a' goes out of bounds. Validate or normalize first.
  • Destroying a very deep trie recurses through the unique_ptr chain, which could overflow the stack for extremely long words.

Phase 5: Variations

Variation 1: Compressed (radix) trie

A chain of nodes with one child each wastes space. A radix trie merges them into a single edge labeled with a substring, so care and card share an edge car and then fork into e and d. This cuts node count sharply for sparse data at the cost of more complex insertion (you sometimes split an edge).

Variation 2: Sorted array plus binary search (no trie)

Keep all queries in a sorted list. Every string starting with p forms one contiguous block, so find its two ends with binary search:

from bisect import bisect_left

def with_prefix(sorted_words: list[str], p: str) -> list[str]:
    lo = bisect_left(sorted_words, p)
    hi = bisect_left(sorted_words, p + "\U0010ffff")   # past any string starting with p
    return sorted_words[lo:hi]

This is O(|p| log N) to find the block, uses only the strings themselves, and is a clean application of the lower-bound idea. The downsides: ranking still needs extra work, and inserting into a sorted list is O(N). It’s a strong baseline and often hard to beat for static data.

Variation 3: Typo-tolerant completion

Users misspell. The idea is to walk the trie while tracking edit distance to the typed prefix, and prune any branch that exceeds a small limit (usually 1 or 2). Elasticsearch’s completion suggester exposes this as a fuzzy option with a configurable fuzziness. The cost is a much wider search, so keep the edit limit small.

Variation 4: Binary trie (maximum XOR)

Store numbers as bit strings, with one level per bit from most significant to least. To maximize x XOR y, greedily walk toward the opposite bit at each level. This solves “Maximum XOR of Two Numbers in an Array” in O(n · 32):

def find_max_xor(nums: list[int]) -> int:
    root: dict = {}
    for x in nums:
        node = root
        for b in range(31, -1, -1):
            node = node.setdefault((x >> b) & 1, {})
    best = 0
    for x in nums:
        node, cur = root, 0
        for b in range(31, -1, -1):
            bit = (x >> b) & 1
            if (bit ^ 1) in node:        # prefer the opposite bit
                cur |= 1 << b
                node = node[bit ^ 1]
            else:
                node = node[bit]
        best = max(best, cur)
    return best

print(find_max_xor([3, 10, 5, 25, 2, 8]))   # 28

Variation 5: Trie-pruned backtracking

In “Word Search II,” you look for many words on a grid. Put all target words in a trie and run one DFS from each cell, walking the trie in step with the grid. The instant the current path isn’t a prefix of any word, you stop. That prune is what makes it fast.

How the options compare

ApproachPrefix lookupMemoryRanked top-kUpdates
Naive scanO(N · |p|)MinimalSort every timeTrivial
Sorted array + binary searchO(|p| log N)LowestNeeds extra structureO(N) insert
Basic trieO(|p|) to reach nodeHigh per nodeSubtree walk (slow for short prefixes)O(L) insert
Trie with cached top-kO(|p|)HighestInstantCostly to keep fresh
Radix trie / FSTO(|p|)Low (compressed)Often built-in via weightsTypically rebuilt

Phase 6: Practice Problems

Easy to hard. Numbers and titles are from LeetCode, so verify them on the site before publishing.

#ProblemDifficultyHint
114. Longest Common PrefixEasyCompare character by character; a trie isn’t required, but it’s good practice to see why.
2208. Implement Trie (Prefix Tree)MediumSeparate “word ends here” from “prefix exists.”
3648. Replace WordsMediumWalk each word through the trie and stop at the first terminal node.
4677. Map Sum PairsMediumStore a value at each terminal, sum over the subtree for a prefix.
51268. Search Suggestions SystemMediumReturn up to three lexicographic matches per typed prefix; sorted array plus binary search works.
6211. Design Add and Search Words Data StructureMediumOn ., branch into every child with DFS.
7421. Maximum XOR of Two Numbers in an ArrayMediumBinary trie, greedy opposite-bit walk.
8212. Word Search IIHardPrune when the path isn’t a trie prefix; consider removing found words.
9745. Prefix and Suffix SearchHardIndex every suffix-plus-word combination, or store suffix#word keys.
10642. Design Search Autocomplete SystemHardThe full problem: cache top-k per node, update counts when the user finishes a sentence.

Phase 7: Common Mistakes and Edge Cases

1. Confusing “prefix exists” with “word exists.” ca is a valid path in our trie but not a stored word. Without a terminal flag, contains("ca") wrongly returns true.

2. Visiting the whole subtree for short prefixes. This is the Phase 2 trap. Measure the one-letter prefix, not just typical ones.

3. Stale rankings. With cached top-k, updating a count means touching every node on that word’s path. Decide up front whether you rebuild in batches or update incrementally.

4. Case and Unicode. If you index iPhone but the user types iphone, you get no match. Normalize (lowercase, trim, Unicode normalization) on both sides, identically.

5. Array children with large alphabets. A 26-slot array is fine for a to z. For emoji or CJK text, use a hash map or a compressed structure.

6. Empty prefix. The empty string leaves you at the root. Decide whether to return global top-k (with the cached version, that’s free) or nothing.

7. Duplicates in the cached build. In TopKTrie, adding the same word twice creates duplicate entries. Aggregate counts first.

8. Deep recursion. Long words and recursive DFS can hit the recursion limit. Use an explicit stack, as above.


Phase 8: Where This Appears in Real Systems

Google Search. Google’s help documentation says Autocomplete predictions reflect searches that have been done on Google, and that its systems start from common and trending queries matching what you’ve typed. It also describes personalization from your past searches and signals like language and location. Google hasn’t publicly detailed the data structures behind this, so treat any specific claim about tries inside Google as inference. What’s public is the product behavior: popularity-ranked prefix matching, with extra signals layered on top.

Elasticsearch. Its completion suggester is the closest public example of the ideas above. The documentation describes building suggestions into a finite-state transducer (FST), a compact graph-like structure that lives in memory and is optimized for fast prefix lookups. A third-party write-up quoting the reference notes that these structures are fast to query but costly to build, and that matching always starts at the beginning of the text. In other words, you get prefix lookup with high speed and high memory use, which are the same trade-offs as our cached trie. Weights on suggestions play the role of our popularity counts, and the fuzzy option covers typo tolerance (Variation 3).

If your suggestions need to match meaning rather than prefixes, that’s a different problem. See vector databases compared for the semantic side. For another data structure hiding behind a familiar feature, read the hidden data structure behind undo/redo. And if you want the tree fundamentals under all of this, see our binary search tree implementation in C++.


Key Takeaways

  • A trie stores strings along shared paths, so lookup cost depends on the prefix length, not the number of stored words.
  • Autocomplete has two problems: finding completions (the trie handles it) and ranking them (where most designs succeed or fail).
  • Walking the full subtree under a short prefix is slow. Cache the top-k at each node to make queries O(|p|).
  • A sorted array with binary search is a strong, low-memory baseline. Don’t reach for a trie by default.
  • Compressed tries (radix trees) and FSTs cut memory, which is why production search engines favor them.
  • Always separate “prefix exists” from “word ends here,” and normalize input consistently.
  • The same structure powers other problems: replace words, wildcard search, Word Search II, and maximum XOR with a binary trie.

FAQ

How does autocomplete work?
Most systems keep a structure indexed by prefix, such as a trie, a sorted list, or an FST. As you type, the system finds the matching prefix, pulls the highest-ranked completions, and returns a handful. Google’s own description is that its predictions start from common and trending searches matching what you’ve typed.

Is a trie the best data structure for autocomplete?
Not always. A trie gives fast incremental prefix lookup, but it’s memory-heavy and doesn’t rank results by itself. A sorted array with binary search, or a compressed structure like an FST, can be a better fit depending on your data size and update rate.

What is the time complexity of a trie?
Insert, search, and prefix-check are all O(L), where L is the string length. Collecting every completion under a prefix is O(S) for a subtree of S nodes, unless you cache top-k results at each node.

How do you rank autocomplete suggestions?
Attach a weight (usually search frequency) to each word and keep the top-k at every trie node. Production systems add other signals, and Google documents personalization, language, and location among them.

What’s the difference between a trie and a radix tree?
A radix tree merges chains of single-child nodes into one edge labeled with a substring. It stores the same strings with far fewer nodes, at the cost of a more complex insert.

Can a trie handle typos?
Yes, with fuzzy matching: you walk the trie while tracking edit distance and prune branches that exceed a small limit. Elasticsearch’s completion suggester offers this through its fuzzy option.

×