Skip to the content.

10. Tries (Prefix Trees)

Back to the index

A tree of characters where each path from the root spells a prefix. Lookups cost O(length of the word), independent of how many words are stored. Used for autocomplete and word games.

How it works

Each trie node maps a character to a child node and has a flag saying whether a word ends there. Words that share a prefix share the path: car, cat and cart all reuse the c -> a nodes.

Diagram

graph TD
    root["root"]
    t_d["d"]
    root --> t_d
    t_c["c"]
    root --> t_c
    t_ca["a"]
    t_c --> t_ca
    t_cat["t - end of cat"]
    t_ca --> t_cat
    t_car["r - end of car"]
    t_ca --> t_car
    t_cart["t - end of cart"]
    t_car --> t_cart
    t_do["o"]
    t_d --> t_do
    t_dog["g - end of dog"]
    t_do --> t_dog

Step-by-step trace

Input: Insert car, cat, cart, dog; then look up car, ca and cow.

Operation Path walked New nodes Result
insert car c -> a -> r 3 end-of-word mark set
insert cat c -> a -> t 1 end-of-word mark set
insert cart c -> a -> r -> t 1 end-of-word mark set
insert dog d -> o -> g 3 end-of-word mark set
look up car c -> a -> r 0 search=True, startsWith=True
look up ca c -> a 0 search=False, startsWith=True
look up cow c 0 stops after ā€˜c’: no child ā€˜o’

Result: ca is a prefix but not a stored word, so search is False while startsWith is True.

Complexity

Operation Time Space
Insert / search / startsWith (word length L) O(L) O(L) new nodes for insert
Total space for all words - O(total characters)

Python reference implementation

class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_word = False


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

    def insert(self, word):
        node, created = self.root, 0
        for ch in word:
            if ch not in node.children:
                node.children[ch] = TrieNode()
                created += 1
            node = node.children[ch]
        node.is_word = True
        return created

    def _walk(self, text):
        node = self.root
        for ch in text:
            node = node.children.get(ch)
            if node is None:
                return None
        return node

    def search(self, word):
        node = self._walk(word)
        return node is not None and node.is_word

    def starts_with(self, prefix):
        return self._walk(prefix) is not None

Common mistakes and tips


The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.

Previous: Heaps and Priority Queues Next: Fenwick Tree (Binary Indexed Tree)