M22 · Tries

Tries: Insert, Search, Prefixes and Delete

A trie stores strings by sharing their prefixes: one node per distinct prefix, one edge per character. Every operation follows a word’s characters from the root, so it costs O(L) whatever the number of stored words. This lesson builds insert, search, startsWith and delete with pruning, and weighs a trie against a hash set and the memory a node really takes.

~40 minIntermediateC# · Python · Java · C++
Curriculum: M22 Tries · 1 of 1 lessons available

You will be able to

  • Describe a trie node (children plus an end-of-word flag) and explain why search and startsWith differ.
  • Trace insert, search, startsWith and delete, including when delete prunes nodes and when it must stop.
  • State the O(L) cost per operation and the space bound, and compare a trie with a hash set honestly.
  • Choose a child representation (fixed array, hash map, sorted list) from the alphabet size and density.
  • Use a trie for autocomplete: find the prefix node, then enumerate its subtree.

Helpful before this lesson

  • M18 Trees — Tree vocabulary, representations and every traversal, recursive and iterative.
  • M06 Strings — Encodings, code units and code points, immutability, and building strings efficiently.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

Write the words car, cart, care and dog as paths from a common starting point, one step per letter, and merge steps that agree. car, cart and care share c → a → r; dog has its own branch. That merged shape is a trie (from retrieval, usually pronounced "try"), also called a prefix tree:

        root
       /    \
      c      d
      |      |
      a      o
      |      |
      r*     g*
     / \
    e*  t*          * = a word ends here
  • The root stands for the empty prefix.
  • Every other node stands for exactly one prefix: the characters on the path from the root to it.
  • Each node knows its children (at most one per character) and whether a stored word ends there.

The end flag is essential. The node for car exists because of cart and care, but only its flag says that car itself was inserted. Without it, a trie could not tell a stored word from a prefix of one. The lab tags word-end nodes with the word they complete.

The four operations

All four start at the root and consume the word one character at a time. Let L be its length.

insert

node = root
for ch in word:
    if node has no child ch: create it
    node = child ch
if node.end: return false     # already stored
node.end = true
return true

Characters shared with words already stored cost nothing new; only the unshared tail creates nodes. Inserting cart after car creates a single node.

search and startsWith

Both walk the same way and differ only in the last line:

find(prefix):
    node = root
    for ch in prefix:
        if node has no child ch: return none
        node = child ch
    return node

search(word)     = find(word) exists and find(word).end
startsWith(p)    = find(p) exists

In the Shared prefixes preset, search("ca") is false (the path exists but no word ends at a) while startsWith("ca") is true. search("cat") stops at a, which has no child t.

delete

Clearing the end flag is enough to make a word disappear, but it can leave a dead branch: nodes that no longer lead to any word. A tidy delete removes them on the way back up:

walk down, remembering the path; if any child is missing: return false
if not last.end: return false          # the path exists, but not as a word
last.end = false
for each node on the path, from the deepest up to (not including) the root:
    if node.end or node has children: stop      # someone else still needs it
    unlink node from its parent
return true

The Delete and prune preset shows both outcomes. Deleting cart unlinks its t node, then stops at r, which ends car and still has the child e. Deleting car afterwards only clears a flag, because care still runs through those nodes. Deleting ca returns false: there is a path, but no word.

After every operation, a trie maintained this way has exactly one node per distinct non-empty prefix of the stored words. The tests in all five places (the lab's engine and four languages) check that invariant against a plain set of strings.

Cost

Operation Time Notes
insert O(L) at most L new nodes
search, startsWith O(L) may stop early at a missing child
delete O(L) walk down, then at most L pruning steps
autocomplete: all words with prefix p O(|p| + size of the subtree) walk to p's node, then enumerate

The striking part is what is missing: n, the number of stored words. Looking up a word in a trie of a million words takes the same number of steps as in a trie of ten. That assumes moving to a child is O(1), which holds for a fixed-size array of children and on average for a hash map.

Space. The node count is at most the total number of characters inserted (less when prefixes are shared), plus the root. What each node costs depends on how it stores children, and that is where tries get expensive.

Is it faster than a hash set?

For exact lookups, not necessarily. Hashing a string reads all L characters too, so a hash-set lookup is also O(L), usually with better cache behaviour: one contiguous string compared against one bucket, instead of L pointer hops through separately allocated nodes. Choose a trie when you need what a hash set cannot do cheaply:

  • Prefix queries: "is anything stored under te?", or list everything under it (autocomplete, routing tables, spell checkers).
  • Ordered iteration: a depth-first walk with children in alphabetical order lists the words sorted, with no sorting step.
  • Longest-prefix matching: walk as far as the input allows and remember the last word end (IP routing, tokenisers).

Node layout and memory

Children stored as Child lookup Memory per node Good for
Fixed array, one slot per letter O(1), no hashing alphabet × pointer size, even if empty small alphabets, dense tries
Hash map from character to child O(1) expected proportional to the actual children, plus map overhead large alphabets (Unicode), sparse tries
Sorted list or array of (character, child) O(log k) or O(k) for k children proportional to the children memory-tight, read-mostly tries

With 26 slots and 8-byte references, an array node spends 208 bytes on child pointers before any other field, and most of those slots are empty in the lower levels of a typical dictionary. That is the classic trie trade-off: speed and simplicity for memory.

Common ways to cut memory:

  • Compressed (radix) tries merge chains of single-child nodes into one edge labelled with a whole substring, so the node count drops to O(number of words).
  • Ternary search trees store three pointers per node (less, equal, greater) and compare characters like a binary search tree.
  • DAWGs / minimal automata also share common suffixes, which suits static dictionaries.

The listings use a 26-slot array in C#, Java and C++ (the direct translation of "one child per letter") and a dict in Python, where an array of 26 Nones would cost more than the handful of children a typical node has.

The teaching implementation

Insert, Search, StartsWith and Delete follow the pseudocode above, with search and startsWith sharing one FindNode walk. Words are validated as non-empty lowercase a–z; anything else is rejected rather than silently mapped to a wrong slot. The listings are the exact files the tests run: each language replays one shared fixture of operation sequences (return values, the sorted list of stored words and the node count after pruning), and then 300 random operation lists over the alphabet abc against a set of strings, where startsWith is checked by scanning the whole set.

Language notes

Language Notes
C# Node?[] Children = new Node?[26], index ch - 'a'. char is a UTF-16 code unit, so this layout only works for a known small alphabet.
Python dict[str, _Node] children and __slots__ to keep nodes small. del parent.children[ch] prunes; an empty dict is falsy, which makes "has children" a plain truth test.
Java Node[] children = new Node[26], ch - 'a'. A pruned node becomes garbage once its parent slot is null.
C++ std::array<std::unique_ptr<Node>, 26>: each node owns its children, so reset() on a slot frees the whole pruned branch with no manual delete. delete is a keyword, hence the method name erase.

Common mistakes

  • No end flag, or treating "the path exists" as "the word exists": search("ca") would be true.
  • Pruning too much: deleting car must not remove nodes that care still uses, and must stop at a node that ends another word.
  • Deleting a prefix that is not a word and clearing nothing but returning true.
  • Assuming a–z input without checking: 'A' - 'a' is negative and indexes outside the array.
  • Counting the trie as O(1) lookup in a comparison with a hash set; both are O(L) in the length of the key.

Edge cases

  • Empty trie: every search and startsWith is false; delete returns false.
  • One word that is a prefix of another (in, inn): both share nodes; deleting inn prunes only the last n.
  • Inserting a word twice: the second insert returns false and changes nothing.
  • The empty string: the lab and the listings reject it. A trie could store it by setting the root's end flag, if your use case needs that.

Worked practice

1. How many nodes (root excluded) does a trie need for tea, ten, ted, to and inn?

Answer

Distinct non-empty prefixes: t, te, tea, ten, ted, to, i, in, inn, so 9 nodes. That is the node count at the end of the Prefix queries preset.

2. You store 10,000 words averaging 8 letters. What is the most nodes the trie can have, and why is the real number usually far lower?

Answer

At most 80,000 (one per character inserted) plus the root, reached only if no two words share even a first letter, which is impossible beyond 26 words over a–z. Real vocabularies share prefixes heavily, so the count is much lower.

3. After inserting car, cart and care, which nodes does delete("car") remove?

Answer

None. It clears the end flag on r, then pruning stops immediately: r still has the children t and e.

4. How would you return every stored word that starts with a prefix p, in alphabetical order?

Answer

Walk to p's node with find(p); if it is missing, return nothing. Otherwise run a depth-first traversal from that node, visiting children from a to z, appending the current string whenever a node's end flag is set. The cost is O(|p|) plus the size of that subtree.

Summary

  • A trie stores one node per distinct prefix; children by character, plus an end-of-word flag.
  • insert, search, startsWith and delete each cost O(L) for a key of length L, independent of n.
  • search needs the end flag; startsWith only needs the path.
  • delete clears the flag, then prunes upward until a node ends another word or has other children.
  • Prefix queries and sorted output are the reason to choose a trie; memory is its main cost, and radix trees or hash-map children reduce it.

Full implementation

The trie in four languages, each checked against one shared fixture of insert, search, startsWith and delete sequences (return values, stored words and node count after pruning) and 300 random operation lists compared with a set of strings.

namespace Bekadan.Dsa.Examples.Tries;
 
/// <summary>
/// A prefix tree over lowercase a-z. Each node holds 26 child slots and an
/// end-of-word flag; every operation costs O(L) for a word of length L.
/// Delete clears the flag, then prunes nodes that no longer lead to a word.
/// </summary>
public sealed class Trie
{
    private sealed class Node
    {
        public readonly Node?[] Children = new Node?[26];
        public bool IsEnd;
    }
 
    private readonly Node _root = new();
 
    /// <summary>Words stored.</summary>
    public int Count { get; private set; }
 
    /// <summary>Nodes allocated, not counting the root.</summary>
    public int NodeCount { get; private set; }
 
    private static void Validate(string word)
    {
        if (word.Length == 0 || word.Any(ch => ch is < 'a' or > 'z'))
            throw new ArgumentException("Words are non-empty and use lowercase a-z only.", nameof(word));
    }
 
    /// <summary>Adds the word; returns false if it was already stored.</summary>
    public bool Insert(string word)
    {
        Validate(word);
        var node = _root;
        foreach (char ch in word)
        {
            int i = ch - 'a';
            if (node.Children[i] is null)
            {
                node.Children[i] = new Node();
                NodeCount++;
            }
            node = node.Children[i]!;
        }
        if (node.IsEnd)
            return false;
        node.IsEnd = true;
        Count++;
        return true;
    }
 
    private Node? FindNode(string prefix)
    {
        Validate(prefix);
        var node = _root;
        foreach (char ch in prefix)
        {
            var child = node.Children[ch - 'a'];
            if (child is null)
                return null;
            node = child;
        }
        return node;
    }
 
    public bool Search(string word)
    {
        var node = FindNode(word);
        return node is not null && node.IsEnd;
    }
 
    public bool StartsWith(string prefix)
    {
        return FindNode(prefix) is not null;
    }
 
    /// <summary>Removes the word; returns false if it was not stored.</summary>
    public bool Delete(string word)
    {
        Validate(word);
        var path = new Node[word.Length + 1];
        path[0] = _root;
        for (int d = 0; d < word.Length; d++)
        {
            var child = path[d].Children[word[d] - 'a'];
            if (child is null)
                return false;
            path[d + 1] = child;
        }
        if (!path[word.Length].IsEnd)
            return false;
        path[word.Length].IsEnd = false;
        Count--;
        for (int d = word.Length; d > 0; d--)
        {
            if (path[d].IsEnd || path[d].Children.Any(c => c is not null))
                break;
            path[d - 1].Children[word[d - 1] - 'a'] = null;
            NodeCount--;
        }
        return true;
    }
 
    /// <summary>Every stored word in alphabetical order (depth-first, children a to z).</summary>
    public List<string> Words()
    {
        var words = new List<string>();
        var buffer = new System.Text.StringBuilder();
        void Walk(Node node)
        {
            if (node.IsEnd)
                words.Add(buffer.ToString());
            for (int i = 0; i < 26; i++)
            {
                if (node.Children[i] is not { } child)
                    continue;
                buffer.Append((char)('a' + i));
                Walk(child);
                buffer.Length--;
            }
        }
        Walk(_root);
        return words;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Tries/Trie.cs

"""A prefix tree over lowercase a-z.
 
Children live in a dict (only the letters actually used take memory). Every operation
costs O(L) for a word of length L. delete clears the end flag, then prunes nodes that
no longer lead to a word.
"""
 
import re
 
_WORD = re.compile(r"[a-z]+")
 
 
class _Node:
    __slots__ = ("children", "is_end")
 
    def __init__(self) -> None:
        self.children: dict[str, _Node] = {}
        self.is_end = False
 
 
def _validate(word: str) -> None:
    if not _WORD.fullmatch(word):
        raise ValueError("words are non-empty and use lowercase a-z only")
 
 
class Trie:
    def __init__(self) -> None:
        self._root = _Node()
        self.count = 0  # words stored
        self.node_count = 0  # nodes allocated, root excluded
 
    def insert(self, word: str) -> bool:
        """Adds the word; returns False if it was already stored."""
        _validate(word)
        node = self._root
        for ch in word:
            if ch not in node.children:
                node.children[ch] = _Node()
                self.node_count += 1
            node = node.children[ch]
        if node.is_end:
            return False
        node.is_end = True
        self.count += 1
        return True
 
    def _find_node(self, prefix: str) -> _Node | None:
        _validate(prefix)
        node = self._root
        for ch in prefix:
            child = node.children.get(ch)
            if child is None:
                return None
            node = child
        return node
 
    def search(self, word: str) -> bool:
        node = self._find_node(word)
        return node is not None and node.is_end
 
    def starts_with(self, prefix: str) -> bool:
        return self._find_node(prefix) is not None
 
    def delete(self, word: str) -> bool:
        """Removes the word; returns False if it was not stored."""
        _validate(word)
        path = [self._root]
        for ch in word:
            child = path[-1].children.get(ch)
            if child is None:
                return False
            path.append(child)
        if not path[-1].is_end:
            return False
        path[-1].is_end = False
        self.count -= 1
        for depth in range(len(word), 0, -1):
            if path[depth].is_end or path[depth].children:
                break
            del path[depth - 1].children[word[depth - 1]]
            self.node_count -= 1
        return True
 
    def words(self) -> list[str]:
        """Every stored word in alphabetical order."""
        out: list[str] = []
 
        def walk(node: _Node, prefix: str) -> None:
            if node.is_end:
                out.append(prefix)
            for ch in sorted(node.children):
                walk(node.children[ch], prefix + ch)
 
        walk(self._root, "")
        return out

Tested on CPython 3.14.0 · examples/python/dsa_examples/trie.py

package dev.bekadan.dsa.tries;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * A prefix tree over lowercase a-z. Each node holds 26 child slots and an end-of-word
 * flag; every operation costs O(L) for a word of length L. delete clears the flag, then
 * prunes nodes that no longer lead to a word.
 */
public final class Trie {
    private static final class Node {
        final Node[] children = new Node[26];
        boolean isEnd;
 
        boolean hasChildren() {
            for (Node child : children) {
                if (child != null) {
                    return true;
                }
            }
            return false;
        }
    }
 
    private final Node root = new Node();
    private int count;
    private int nodeCount;
 
    /** Words stored. */
    public int count() {
        return count;
    }
 
    /** Nodes allocated, not counting the root. */
    public int nodeCount() {
        return nodeCount;
    }
 
    private static void validate(String word) {
        if (!word.matches("[a-z]+")) {
            throw new IllegalArgumentException("Words are non-empty and use lowercase a-z only.");
        }
    }
 
    /** Adds the word; returns false if it was already stored. */
    public boolean insert(String word) {
        validate(word);
        Node node = root;
        for (char ch : word.toCharArray()) {
            int i = ch - 'a';
            if (node.children[i] == null) {
                node.children[i] = new Node();
                nodeCount++;
            }
            node = node.children[i];
        }
        if (node.isEnd) {
            return false;
        }
        node.isEnd = true;
        count++;
        return true;
    }
 
    private Node findNode(String prefix) {
        validate(prefix);
        Node node = root;
        for (char ch : prefix.toCharArray()) {
            Node child = node.children[ch - 'a'];
            if (child == null) {
                return null;
            }
            node = child;
        }
        return node;
    }
 
    public boolean search(String word) {
        Node node = findNode(word);
        return node != null && node.isEnd;
    }
 
    public boolean startsWith(String prefix) {
        return findNode(prefix) != null;
    }
 
    /** Removes the word; returns false if it was not stored. */
    public boolean delete(String word) {
        validate(word);
        Node[] path = new Node[word.length() + 1];
        path[0] = root;
        for (int d = 0; d < word.length(); d++) {
            Node child = path[d].children[word.charAt(d) - 'a'];
            if (child == null) {
                return false;
            }
            path[d + 1] = child;
        }
        if (!path[word.length()].isEnd) {
            return false;
        }
        path[word.length()].isEnd = false;
        count--;
        for (int d = word.length(); d > 0; d--) {
            if (path[d].isEnd || path[d].hasChildren()) {
                break;
            }
            path[d - 1].children[word.charAt(d - 1) - 'a'] = null;
            nodeCount--;
        }
        return true;
    }
 
    /** Every stored word in alphabetical order. */
    public List<String> words() {
        List<String> out = new ArrayList<>();
        collect(root, new StringBuilder(), out);
        return out;
    }
 
    private static void collect(Node node, StringBuilder prefix, List<String> out) {
        if (node.isEnd) {
            out.add(prefix.toString());
        }
        for (int i = 0; i < 26; i++) {
            if (node.children[i] != null) {
                prefix.append((char) ('a' + i));
                collect(node.children[i], prefix, out);
                prefix.setLength(prefix.length() - 1);
            }
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/tries/Trie.java

#pragma once
 
#include <algorithm>
#include <array>
#include <cstddef>
#include <memory>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
 
namespace bekadan::dsa {
 
// A prefix tree over lowercase a-z. Each node owns 26 child slots and an end-of-word
// flag; every operation costs O(L) for a word of length L. erase clears the flag, then
// prunes nodes that no longer lead to a word (`delete` is a C++ keyword).
class Trie {
    struct Node {
        std::array<std::unique_ptr<Node>, 26> children{};
        bool is_end = false;
 
        [[nodiscard]] bool has_children() const {
            return std::ranges::any_of(children, [](const auto& c) { return c != nullptr; });
        }
    };
 
public:
    [[nodiscard]] std::size_t size() const noexcept { return count_; }
    // Nodes allocated, not counting the root.
    [[nodiscard]] std::size_t node_count() const noexcept { return node_count_; }
 
    // Adds the word; returns false if it was already stored.
    bool insert(std::string_view word) {
        validate(word);
        Node* node = &root_;
        for (const char ch : word) {
            auto& slot = node->children[index(ch)];
            if (!slot) {
                slot = std::make_unique<Node>();
                ++node_count_;
            }
            node = slot.get();
        }
        if (node->is_end) return false;
        node->is_end = true;
        ++count_;
        return true;
    }
 
    [[nodiscard]] bool search(std::string_view word) const {
        const Node* node = find_node(word);
        return node != nullptr && node->is_end;
    }
 
    [[nodiscard]] bool starts_with(std::string_view prefix) const {
        return find_node(prefix) != nullptr;
    }
 
    // Removes the word; returns false if it was not stored.
    bool erase(std::string_view word) {
        validate(word);
        std::vector<Node*> path{&root_};
        for (const char ch : word) {
            Node* child = path.back()->children[index(ch)].get();
            if (child == nullptr) return false;
            path.push_back(child);
        }
        if (!path.back()->is_end) return false;
        path.back()->is_end = false;
        --count_;
        for (std::size_t d = word.size(); d > 0; --d) {
            if (path[d]->is_end || path[d]->has_children()) break;
            path[d - 1]->children[index(word[d - 1])].reset();  // frees the node
            --node_count_;
        }
        return true;
    }
 
    // Every stored word in alphabetical order.
    [[nodiscard]] std::vector<std::string> words() const {
        std::vector<std::string> out;
        std::string prefix;
        collect(root_, prefix, out);
        return out;
    }
 
private:
    static void validate(std::string_view word) {
        if (word.empty() || !std::ranges::all_of(word, [](char c) { return c >= 'a' && c <= 'z'; }))
            throw std::invalid_argument("words are non-empty and use lowercase a-z only");
    }
 
    static std::size_t index(char ch) { return static_cast<std::size_t>(ch - 'a'); }
 
    [[nodiscard]] const Node* find_node(std::string_view prefix) const {
        validate(prefix);
        const Node* node = &root_;
        for (const char ch : prefix) {
            const Node* child = node->children[index(ch)].get();
            if (child == nullptr) return nullptr;
            node = child;
        }
        return node;
    }
 
    static void collect(const Node& node, std::string& prefix, std::vector<std::string>& out) {
        if (node.is_end) out.push_back(prefix);
        for (std::size_t i = 0; i < node.children.size(); ++i) {
            if (!node.children[i]) continue;
            prefix.push_back(static_cast<char>('a' + i));
            collect(*node.children[i], prefix, out);
            prefix.pop_back();
        }
    }
 
    Node root_;
    std::size_t count_ = 0;
    std::size_t node_count_ = 0;
};
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/trie.hpp

References