Tries

How a trie stores words letter by letter, how it answers prefix and autocomplete queries, and what interviewers ask about it.

16 minLesson 5 of 6
On this page
  1. How a trie is structured
  2. How insert, search and autocomplete work
  3. Code
  4. Time and space
  5. Variants and alternatives
  6. Pitfalls
  7. In the interview
  8. What to practise next

A trie is a tree that stores a set of strings one letter per edge, so that strings with the same beginning share the same path from the root. It answers questions about prefixes, such as "does any stored word start with su?" and "list every word that starts with su", in time that depends on the length of the prefix and not on the number of stored words. You reach for it when a problem asks for autocomplete, prefix matching or searching a grid for words from a dictionary.

Without a trie, a prefix query has to compare the prefix against every stored word, which gets slower as the word list grows. A trie does the work once, while inserting, by putting every word starting with su under the same node.

How a trie is structured

The word "trie" comes from retrieval and is usually pronounced "try". Each edge is labelled with a letter, and the path from the root to a node spells a prefix. Each node holds two things.

  • children is a map from each letter that can follow this prefix to the next node.
  • isWord says whether a stored word ends at this node.

The flag is needed because a word can be a prefix of another word. The words so and sort both pass through the node for so, and only the flag tells you that so is a word while sor is not.

node for "so" isWord: true children: { r: ● } node for "sor" isWord: false children: { t: ● } "sor" is on the path to "sort" but is not a word itself
Two trie nodes. A node does not store its own letter, because the letter belongs to the edge that leads to it.

How insert, search and autocomplete work

To insert a word, start at the root and handle one letter at a time. Move to the child for that letter, creating it if it does not exist, and after the last letter set the flag on the node you reached.

To search, walk the same way, but stop if a letter has no child, because then nothing stored starts with that prefix. If you reach the end of the prefix, you are on the prefix's node. To ask "is this exact word stored?", check that node's flag. To ask "does any word start with this?", it is enough that the node exists. To autocomplete, collect every flagged node in the subtree below it.

The trace below inserts five words and then asks three questions. The letter in each circle is the letter on the edge into it, and green nodes have the flag set, with the word written next to them.

Insert so, sort, sun, sum, sky, then searchUse the arrows or ← → keys
insert(word):  node = root  for each letter: go to (or create) that child  mark node as the end of a word find(prefix):  node = root  for each letter: go to that child, or stop if missing  return node
  1. •

    1An empty trie is a single root node, drawn as a dot, which stands for the empty prefix.

  2. •soso

    2Insert so. The insert creates s and then o below it, and flags o. A green node means a word ends there.

  3. •sosortsort

    3Insert sort. The insert walks down the existing s and o, creates the new nodes r and t, and flags t. The node o stays green because so is still a word.

  4. •sosortsortunsun

    4Insert sun. The word shares only s with the existing words, so a new branch starts below s.

  5. •sosortsortunsunmsum

    5Insert sum. The word shares s and u with sun, so only one new node is needed.

  6. •sosortsortunsunmsumkysky
    words
    5
    letters
    15
    nodes
    9

    6Insert sky. The five words have 15 letters in total, but because they share prefixes the trie needs only 9 letter nodes.

  7. •sosortsortunsunmsumkysky

    7To autocomplete su, the search starts at the root and follows s.

  8. •sosortsortunsunmsumkysky

    8It then follows u. That is two steps, one per letter, however many words are stored. Every word below this node starts with su, and the other branches are never visited.

  9. •sosortsortunsunmsumkysky
    suggestions
    sun, sum

    9The green nodes below u are sun and sum, and these are the suggestions.

  10. •sosortsortunsunmsumkysky
    has(sor)
    false
    startsWith(sor)
    true

    10To check whether sor is a word, the search follows s, o and r. The path exists, but r is not green, so sor is not a word, although it is the start of sort.

  11. •sosortsortunsunmsumkysky
    has(sea)
    false

    11To check whether sea is a word, the search reaches s, which has no e child, and stops after the first letter. A word that is not stored is often rejected before its last letter.

1 / 11

Code

The children map works for any alphabet, including capital letters, digits and accented characters.

class TrieNode {
  constructor() {
    this.children = new Map(); // letter -> TrieNode
    this.isWord = false;       // does a word end here?
  }
}
 
class Trie {
  constructor() { this.root = new TrieNode(); }
 
  insert(word) {
    let node = this.root;
    for (const ch of word) {
      if (!node.children.has(ch)) node.children.set(ch, new TrieNode());
      node = node.children.get(ch);
    }
    node.isWord = true; // mark the end of the word
  }
 
  // Follow prefix letter by letter. null if the path breaks.
  find(prefix) {
    let node = this.root;
    for (const ch of prefix) {
      node = node.children.get(ch);
      if (node === undefined) return null;
    }
    return node;
  }
 
  has(word) {
    const node = this.find(word);
    return node !== null && node.isWord;
  }
 
  startsWith(prefix) { return this.find(prefix) !== null; }
}
class TrieNode:
    def __init__(self):
        self.children = {}    # letter -> TrieNode
        self.is_word = False  # does a word end here?
 
class Trie:
    def __init__(self):
        self.root = TrieNode()
 
    def insert(self, word):
        node = self.root
        for ch in word:
            if ch not in node.children:
                node.children[ch] = TrieNode()
            node = node.children[ch]
        node.is_word = True  # mark the end of the word
 
    # Follow prefix letter by letter. None if the path breaks.
    def find(self, prefix):
        node = self.root
        for ch in prefix:
            node = node.children.get(ch)
            if node is None:
                return None
        return node
 
    def has(self, word):
        node = self.find(word)
        return node is not None and node.is_word
 
    def starts_with(self, prefix):
        return self.find(prefix) is not None

Autocomplete is find followed by a preorder traversal of the subtree below the prefix node. The traversal builds each word as it walks down.

// Every stored word that begins with prefix.
function complete(trie, prefix) {
  const out = [];
  const start = trie.find(prefix);
  if (start === null) return out;
  const walk = (node, word) => {
    if (node.isWord) out.push(word);
    for (const [ch, child] of node.children) walk(child, word + ch);
  };
  walk(start, prefix);
  return out;
}
 
const trie = new Trie();
for (const w of ["so", "sort", "sun", "sum", "sky"]) trie.insert(w);
complete(trie, "su"); // ["sun", "sum"]
trie.has("sor");      // false
trie.startsWith("sor"); // true
# Every stored word that begins with prefix.
def complete(trie, prefix):
    out = []
    start = trie.find(prefix)
    if start is None:
        return out
 
    def walk(node, word):
        if node.is_word:
            out.append(word)
        for ch, child in node.children.items():
            walk(child, word + ch)
 
    walk(start, prefix)
    return out
 
trie = Trie()
for w in ["so", "sort", "sun", "sum", "sky"]:
    trie.insert(w)
complete(trie, "su")      # ['sun', 'sum']
trie.has("sor")           # False
trie.starts_with("sor")   # True

Time and space

Every operation visits one node per letter, so for a word of length L, insert, has and startsWith each take O(L) steps, whether the trie holds 5 words or 5 million. Autocomplete adds the work of reading the subtree under the prefix, which grows with the number of suggestions and their length.

The trie has at most one node per inserted letter, and fewer when words share prefixes. Each node carries its own map, though, so a trie usually takes more memory than a plain list of the same words.

ApproachTimeSpaceWhy
Hash set of wordsO(L) lookupO(total letters)Answers "is this exact word stored?" well. A prefix question has to check every word, which is O(n · L).
TrieO(L) per operationO(total letters)One node per letter at most. Autocomplete adds the size of the answer.

Variants and alternatives

Array children instead of a map

When the alphabet is small and fixed, such as lowercase English letters, each node can hold an array of 26 child slots and index it with ch - 'a'. This is faster than a map and is common in interview solutions. The cost is memory, because most of the 26 slots in most nodes are empty, and the array breaks on capital letters, digits or accented characters. Use a map when the alphabet is large or unknown.

Storing a count or a stored value at each node

Instead of a boolean, a node can hold a number. A counter of how many words pass through the node gives the number of words with a given prefix without traversing the subtree. A counter of how many words end at the node lets the trie store duplicates. A stored value turns the trie into a map from strings to values, which is how a prefix-sum or word-frequency problem is usually solved.

Deleting a word

The simple way to delete a word is to clear its flag. The nodes stay in the trie, which wastes memory but keeps every other word intact. To free memory, walk back up after clearing the flag and remove each node that has no children and is not flagged, stopping at the first node that is still needed. If you remove nodes without that check, you cut off other words that share the path.

Compressed tries

In a compressed trie, also called a radix tree, a chain of nodes that each have a single child is merged into one edge labelled with a whole string. A trie holding only international becomes one edge instead of thirteen nodes. Lookups still depend on the length of the word, but the structure uses far fewer nodes when the words are long and mostly different.

Searching with a wildcard

Some problems let a query contain a wildcard such as ., which matches any single letter, so that s.n matches sun. The search walks the trie recursively. A normal letter follows one child, as before. A wildcard tries every child in turn and succeeds if any of them leads to a match. A query without wildcards is still O(L), but each wildcard can multiply the work by the number of children, so a query made only of wildcards visits the whole trie.

Binary tries

A trie does not have to be built from letters. Inserting each number as a fixed-length string of bits gives a trie in which every node has at most two children. This is the standard tool for questions such as "find the pair in the array with the largest XOR". For each number, you walk down the trie and at every bit prefer the child with the opposite bit, because that makes the XOR bit a 1. The work per number is proportional to the number of bits, not to the size of the array.

When a trie is not the right tool

If you only need to know whether an exact word is stored, a hash set is simpler and smaller. If the word list never changes, a sorted array with binary search can find the range of words that share a prefix without building any nodes. A trie also does not help with matching a pattern inside a long text, which is a job for the algorithms in string matching.

Pitfalls

In the interview

The signals that a problem needs a trie are a set of words that is queried many times by prefix, a request to suggest or complete words, a need to stop a search as soon as the current partial word cannot lead to any dictionary word, or a task that compares many strings by their shared beginnings. The grid word search with a list of words is the common case: the trie lets one search of the grid look for all the words at once and abandon a path the moment its letters match no word.

Interviewers commonly ask the following questions.

  • "Why a trie and not a hash set?" A hash set answers whether an exact word is stored, but it cannot answer a prefix question without checking every word. A trie follows the prefix directly, so the cost depends on the prefix length. If the problem only needs exact lookups, a hash set is the better choice.
  • "What is the time and space complexity?" Insert and search take O(L) for a word of length L. Space is O(total letters) in the worst case, when the words share nothing, and each node carries the overhead of its map or array.
  • "How would you return the top three suggestions for a prefix?" Store a frequency with each word. After finding the prefix node, either traverse the subtree and keep the best three, or save the best three at every node while inserting so that a query only reads one node. The second approach answers queries faster but uses more memory and must be updated when frequencies change.
  • "Array or map for the children?" An array of 26 is quick and simple when the input is lowercase letters. A map handles any alphabet and uses less memory when nodes have few children.
  • "How would you delete a word?" Clear the flag. If memory matters, also remove the nodes on the path that have no other children and are not flagged, working from the end of the word upward.
  • "How would you use a trie to find words in a grid?" Insert all the words, then run a backtracking search from each cell while moving down the trie in step with the path. When the current node has no child for the next cell's letter, stop that path. When the node is flagged, record the word.
  • "How would you support a wildcard in the query?" Search recursively. A normal letter follows its single child, and a wildcard tries every child and returns true if any branch matches. Say that the worst case grows with the size of the trie, because a query of only wildcards can visit every node.
  • "How could the trie use less memory?" Merge chains of single-child nodes into one edge, which gives a compressed trie, or store the children in a sorted array and search it instead of using a map.
Quick check

The trie holds so, sort, sun, sum and sky. How many new nodes does inserting sold create?

In the same trie, what does has("su") return?

A trie holds 1 million words. Roughly how many steps does has("summer") take?

What to practise next

Practise a grid word search with backtracking, where a trie lets you cut off paths early. Balanced Trees covers the other kind of tree that keeps lookups fast, by keeping the tree short whatever order the data arrives in.