Tries (Prefix Trees)

Data Structures & Algorithms · Trees & Heaps · Advanced · 14 min

The data structure behind autocomplete and spell-check.

A tree of letters growing down from a root. "car", "cart" and "care" all walk the same c → a → r branch and only split at the end. A small flag ($) hangs on every node where a real word stops.

The idea in everyday words

A dictionary's thumb tabs: to find 'cart' you go to C, then A, then R, then T. Words that share a beginning share the same path. 'car', 'cart' and 'care' all walk through c → a → r.

Build it with nested dictionaries

Each node is a dict of children; a special key marks 'a word ends here'.

def build(words):
    root = {}
    for w in words:
        node = root
        for ch in w:
            node = node.setdefault(ch, {})
        node["
quot;] = True return root trie = build(["car", "cart", "care", "dog"]) print(list(trie.keys())) # first letters print(list(trie["c"]["a"]["r"].keys())) # what follows 'car'

Search & prefix search

def walk(trie, s):
    node = trie
    for ch in s:
        if ch not in node:
            return None
        node = node[ch]
    return node

trie = {"c": {"a": {"r": {"
quot;: True, "t": {"
quot;: True}}}}} print("has word car:", "
quot; in (walk(trie, "car") or {})) print("prefix ca exists:", walk(trie, "ca") is not None) print("has word ca:", "
quot; in (walk(trie, "ca") or {}))

Lookup costs O(length of word), independent of how many words are stored!

Step by step

  1. insert car:

    root → c → a → r ($)

  2. insert cart:

    reuse c → a → r, add t ($)

  3. search 'cat':

    c ✓ a ✓ t ✗ → not found

  4. prefix 'ca':

    path exists → 2 words below it

Code example

def autocomplete(words, prefix):
    root = {}
    for w in words:
        node = root
        for ch in w:
            node = node.setdefault(ch, {})
        node["
quot;] = w node = root for ch in prefix: if ch not in node: return [] node = node[ch] out, stack = [], [node] while stack: n = stack.pop() for k, v in n.items(): if k == "
quot;: out.append(v) else: stack.append(v) return sorted(out) print(autocomplete(["car", "cart", "care", "dog", "cat"], "car"))

Complexity

  • Time: O(L) insert / search
  • Space: O(total characters)

Interview tips

  • Implement Trie, Word Search II, Replace Words, Autocomplete system.

  • Mention the end-of-word marker explicitly.

Challenge: Count Words With a Prefix

Build a trie from words and return how many distinct words start with prefix.

Example: count_prefix(["car", "cart", "dog", "care"], "car") → 3

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Trees & Heaps

Previous: Heaps & Priority Queues · Next: Graphs & Grids