Tries · O(L) per operation

Trie

Insert, search, prefix queries and delete with pruning over a–z.

The full explanation, derivation and practice are in the lesson Tries: insert, search, prefixes and delete.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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