Lesson 18 · Non-linear structures

Trie Operations and Applications

Every trie operation walks down one edge per character. Insert creates missing nodes, search checks the end flag, prefix search ignores it, and delete prunes only nodes no other word needs.

Trie Operations and Applications concept diagramA trie holding car and cat. Inserting card walks c, a, r and creates one new node d. Searching ca returns false because a is not a word end, while startsWith ca returns true. Deleting card removes only d, and car still ends at r. Every operation costs O(L).●catrdcatcarcardgreen = end of a word · blue = new nodeinsert("card")walk c, a, r, then create d and mark it a word endsearch("ca") → falsethe path exists, but a is not a word endstartsWith("ca") → truethe path exists; end marks are ignoreddelete("card")unmark d and prune it; car still ends at revery operation costs O(L), L = word length
1

What a Node Has to Hold

A trie implementation needs one node type with two fields: a children map from a character to a child node, and a boolean isEndOfWord. Every operation below reads or writes only these two fields. What a trie is and when to use one is covered in tries.

A node stores no character of its own. The character belongs to the edge that leads to it, which is the key its parent stores it under. The root stands for the empty prefix and is flagged only if the empty string is stored.

For children, an array of 26 indexed by c - 'a' is fastest when keys are lowercase letters. A hash map stores only the children that exist and handles any alphabet. The Python code below uses a dictionary; the C++ and Java versions use arrays of 26.

Some implementations also keep a count of words passing through each node. It costs one integer per node and makes deletion and 'how many words start with p' simple, as shown below.

  • Node = children + isEndOfWord (+ an optional pass-through count)
  • Pick the array for speed on a small fixed alphabet, the map for anything else
2

Trie Insertion

  1. Start at the root
  2. For each character: follow the child if it exists, otherwise create it and move into it
  3. After the last character, set isEndOfWord on the current node

Inserting car into an empty trie creates c, a and r and flags r. Inserting card next follows c, a and r and creates only d. Inserting car again creates nothing and sets a flag that is already true.

The last step is the one that records the word. Code that forgets it builds every path correctly and then answers false to every search.

Insertion costs O(L) time for a word of length L and creates at most L nodes, however many words are already stored.

With a pass-through count, add one to each node on the path, but only when the word is new: check the end flag first, or a duplicate insert inflates every count.

  • Empty string: no loop runs; the root gets flagged
  • Duplicate word: no new nodes, flag unchanged
3

Trie Search and Prefix Search

search(word) and startsWith(prefix) do the same walk: from the root, move to the child for each character, and return false the moment a child is missing.

They differ only at the end. search returns the end flag of the node reached: in a trie holding car, card and cat, the walk for ca succeeds but a is not flagged, so ca is not a stored word. startsWith returns true as soon as the walk succeeds, because some word passes through that node.

Swapping the two is the most common trie bug: with the startsWith check in search, every prefix is reported as a stored word.

Both cost O(L) and allocate nothing. A miss stops at the first missing character, so searching cab stops after two steps. That early exit is why tries reject non-words quickly.

Completions, the core of autocomplete, extend startsWith: walk to the prefix node, then run a depth-first search of its subtree and collect every flagged node. For car that gives car and card, in O(L + k) for k results. Visiting children in letter order returns them sorted.

The operations side by side
OperationWalkAt the endCost
insert(word)Follow or createSet isEndOfWordO(L)
search(word)Follow onlyReturn isEndOfWordO(L)
startsWith(p)Follow onlyReturn trueO(L)
completions(p)Follow to pDFS the subtreeO(L + k)
delete(word)Follow to the endClear the flag, prune upwardO(L)
Key reference

Terms, operations, and practical uses

Structure

  • Prefix sharingWords with the same start share the nodes for their common letters.
  • Child pointersThe character lives on the edge to the child; children are kept in an array of 26 or a hash map.
  • End-of-word flagTrue on a node where a stored word ends.

Operations

  • InsertionFollow existing children, create missing ones, flag the last node.
  • Word searchWalk the characters; the word exists only if the walk succeeds and the last node is flagged.
  • Prefix searchWalk the characters; the prefix exists if the walk succeeds. Its subtree holds the completions.

Variants

  • Radix trieAlso called a Patricia trie. Merges chains of single-child nodes into one edge labelled with a string.
  • Binary trieEdges are bits 0 and 1. Used to find the maximum XOR of a number with any stored number.
  • Aho–CorasickA trie of patterns plus failure links, finding every pattern in a text in one pass.
Implementation

Code in Python, C++ and Java

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 char in word:
            if char not in node.children:
                node.children[char] = TrieNode()
            node = node.children[char]
        node.is_word = True
    def starts_with(self, prefix):
        node = self.root
        for char in prefix:
            if char not in node.children:
                return []
            node = node.children[char]
        words = []
        def collect(node, path):
            if node.is_word:
                words.append(prefix + path)
            for char, child in sorted(node.children.items()):
                collect(child, path + char)
        collect(node, '')
        return words

trie = Trie()
for word in ('car', 'cat'):
    trie.insert(word)
print('Completions of "ca":', ', '.join(trie.starts_with('ca')))
#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct TrieNode {
    TrieNode* children[26] = {nullptr};
    bool isWord = false;
};
class Trie {
    TrieNode* root = new TrieNode();
    void collect(TrieNode* node, string prefix, vector<string>& out) {
        if (node->isWord) out.push_back(prefix);
        for (int c = 0; c < 26; c++)
            if (node->children[c]) collect(node->children[c], prefix + char('a' + c), out);
    }
public:
    void insert(string word) {
        TrieNode* node = root;
        for (char c : word) {
            if (!node->children[c - 'a']) node->children[c - 'a'] = new TrieNode();
            node = node->children[c - 'a'];
        }
        node->isWord = true;
    }
    vector<string> startsWith(string prefix) {
        TrieNode* node = root;
        for (char c : prefix) {
            if (!node->children[c - 'a']) return {};
            node = node->children[c - 'a'];
        }
        vector<string> out;
        collect(node, prefix, out);
        return out;
    }
};

int main() {
    Trie trie;
    trie.insert("car");
    trie.insert("cat");
    vector<string> words = trie.startsWith("ca");
    cout << "Completions of \"ca\": ";
    for(size_t i = 0; i < words.size(); i++) {
      if (i) cout << ", ";
      cout << words[i];
    }
    cout << '\n';
}
import java.util.*;

public class Main {
    static class TrieNode {
        TrieNode[] children = new TrieNode[26];
        boolean isWord = false;
    }

    static class Trie {
        TrieNode root = new TrieNode();
        public void insert(String word) {
            TrieNode node = root;
            for (char c : word.toCharArray()) {
                if (node.children[c - 'a'] == null) node.children[c - 'a'] = new TrieNode();
                node = node.children[c - 'a'];
            }
            node.isWord = true;
        }
        public List<String> startsWith(String prefix) {
            TrieNode node = root;
            for (char c : prefix.toCharArray()) {
                if (node.children[c - 'a'] == null) return List.of();
                node = node.children[c - 'a'];
            }
            List<String> out = new ArrayList<>();
            collect(node, prefix, out);
            return out;
        }
        private void collect(TrieNode node, String prefix, List<String> out) {
            if (node.isWord) out.add(prefix);
            for (int c = 0; c < 26; c++)
                if (node.children[c] != null) collect(node.children[c], prefix + (char) ('a' + c), out);
        }
    }

    public static void main(String[] args) {
        Trie trie = new Trie();
        trie.insert("car");
        trie.insert("cat");
        System.out.println("Completions of \"ca\": " + String.join(", ", trie.startsWith("ca")));
    }
}
Watch it run

Step through it

Running on insert car, card, cat; search, complete, delete

empty trie·operationnextinsert carnodes1
Step 1

Start: only the root

A new trie is one root node with no children and no end flag. Every operation below starts here and moves down one edge per character.

Output
1 / 14
4

Trie Deletion, Case by Case

  1. Walk to the word's last node; if the path is missing or the flag is false, the word is not stored: stop
  2. Clear isEndOfWord
  3. Walk back up: remove the node if it has no children and is not flagged
  4. Stop at the first node that has a child or ends another word

Deletion is the one trie operation that can damage other data, because nodes on the path may belong to other words too. Removing the whole path of car from a trie that also holds card and cat removes c, a and r, and takes card and cat with them.

Three cases show the rule. Deleting car from a trie holding only car removes all three nodes. Deleting car when card is also stored removes nothing: r has the child d, so pruning stops at once and only the flag changes. Deleting card afterwards removes d, then r (no children, flag already cleared), and stops at a, which still has t.

Clearing the flag alone is already correct: searches give the right answers and only some unused nodes remain. Pruning just reclaims memory, so programs that rarely delete often skip it.

With the pass-through count, deletion needs no case analysis: subtract one on every node along the path and drop any node whose count reaches zero. All operations stay O(L).

  • Deleting a word that was never inserted must change nothing
  • Recursive delete returns 'remove me' to the parent; iterative delete keeps the path in a list
5

Autocomplete and Other Uses

Autocomplete: completions of the typed prefix, often ranked by a frequency stored on each flagged node. Spell checking: search rejects a non-word at its first missing letter, and nearby branches suggest corrections. Word grids: Word Search II walks a trie while walking the grid, so one search finds every listed word at once.

Two extensions build on the same operations. A binary trie inserts numbers bit by bit to answer maximum-XOR queries. Aho–Corasick adds failure links to a trie of patterns and finds all of them in one pass over a text.