Essential Data Structures home

Trie

A tree that stores words by their letters, one character per step. Words that share a beginning share the same path, which makes prefix search almost free. It is the structure behind autocomplete.

root c d a t r o g
Illustration: a trie holding "cat", "car", and "dog". The words "cat" and "car" share the path c, a, and green circles mark the ends of words.

What it is

A trie, pronounced "try" and short for retrieval tree, is a tree where each edge is labelled with one character and each node stands for a prefix. The root stands for the empty string. Walking down from the root spelling out a word reaches the node for that word, and nodes at the end of a real word are marked, so a node can be both a prefix of longer words and a complete word itself.

Words that start the same way share the same path. In the picture, "cat" and "car" share the nodes for c and a, and only split at the last letter. That sharing is the whole idea: a trie stores a set of words by their common prefixes instead of storing each word separately.

Every node holds a link to each child letter it has, often in a small map from character to child node, plus a flag that says whether a word ends here. The trie does not store whole words anywhere. A word exists in the trie exactly when its path exists and its last node is flagged.

How it works

To insert a word, start at the root and follow or create one edge per letter. When the last letter is reached, mark the node as the end of a word. To search, follow the same path, and check the flag at the end: if any edge is missing, the word is not there, and if the path exists but the flag is clear, the word is only a prefix of a longer word, not a word itself.

Prefix search works the same way, and it is where a trie earns its keep. Follow the prefix to its node, then walk the subtree below it to collect every word that starts with that prefix. A hash table can answer whether a word exists just as fast, but it cannot list all words starting with "ca" without scanning everything. A trie answers it by walking one small subtree.

Deleting a word unmarks its end flag, then removes any nodes that are left with no children and no end flag, walking back up the path. That cleanup keeps the trie from holding dead branches for words that no longer exist.

Complexity

OperationAverageWorst case
Insert a wordO(m)O(m)
Search for a wordO(m)O(m)
Prefix searchO(m + k)O(m + k)
Delete a wordO(m)O(m)
SpaceO(n x m)O(n x m)

m is the length of the word or prefix, n is the number of words, and k is the number of words that match the prefix. The cost depends on the length of the word, not on how many words are stored, which is why a trie stays fast as the dictionary grows. Space is large in the worst case, but shared prefixes keep real dictionaries much smaller.

When to use it, and when not to

Use a trie when the work is about prefixes: autocomplete, spell checking, predictive text, IP routing tables, and finding all words that start with a given string. It is also a good fit when you need words in alphabetical order, since walking the trie in order lists them sorted.

Do not use a trie when you only need to test whether exact words exist, or when memory is tight. A hash table answers exact lookups in the same time with far less space. A trie also spends a node per character, so short keys with little shared prefix waste the most memory, and that is where a hash table or a sorted list fits better.

Where you meet it

Every time a search box suggests completions as you type, a trie, or a close cousin, is doing the work. Phone keyboards suggest the next word from one. Spell checkers walk a trie to find near matches for a mistyped word. Routers match IP address prefixes in a binary trie, and DNA sequence databases store long strings in tries because the shared prefixes are large.

In Python

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

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

    def insert(self, word):
        node = self.root
        for ch in word:
            node = node.children.setdefault(ch, TrieNode())
        node.is_word = True

    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

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

trie = Trie()
for word in ["cat", "car", "dog"]:
    trie.insert(word)

print(trie.search("cat"))        # True
print(trie.search("ca"))         # False, only a prefix
print(trie.starts_with("ca"))    # True
print(trie.starts_with("do"))    # True

In short: a trie trades memory for prefix power. Shared paths make finding every word that starts a certain way as cheap as spelling the prefix.

Sources

← Home