Data structure · Trees and heaps
Trie
A tree of characters where each path from the root spells a prefix: insert, lookup and prefix queries in O(L) for a word of length L.
The derivations, edge cases and exercises are in the lesson Tries: insert, search, prefixes and delete. Open it full width in the playground.
On this page
The idea
Each node has at most one child per character and a flag that marks the end of a word. Inserting a word walks or creates one node per character; a prefix query stops at the prefix’s node and everything below it starts with that prefix.
The cost depends on the word length, not on how many words are stored. Memory is the trade-off: every node carries its own child table, so a trie usually needs much more memory than a flat set of the same words.
Representation. Nodes with a child map keyed by character and an end-of-word flag, from a root that stands for the empty prefix. The lab limits words to a–z.
Operations
| Operation | Time | Extra space | Notes |
|---|---|---|---|
| Insert word | O(L) | O(L) new nodes at most | |
| Search word | O(L) | O(1) | |
| Starts with prefix | O(L) | O(1) | Listing the k matching words adds the size of that subtree. |
| Delete word | O(L) | O(L) recursion | Prunes nodes that no longer lead to a word. |
Invariants
What stays true before and after every operation.
- A word is stored exactly when its path exists and the last node is marked end-of-word.
- Every node except the root lies on the path of at least one stored word (after pruning).
When to use it
Use it when
- You answer many prefix queries: autocomplete, spell checking, routing tables.
- You need words in lexicographic order from a walk of the tree.
Avoid it when
- You only need exact lookups: a hash set uses far less memory.
- The alphabet is large and sparse; use a map per node or a compressed trie.
Built-in equivalents
What the standard library of each language offers. Linked types have a full page in the collections encyclopedia with every operation’s complexity, memory effects and a tested example.
C#
No trie in the base library; a node with a Dictionary<char, Node> or a 26-slot array is the usual build.
Python
No trie in the standard library; nested dicts are the common quick version.
Java
No trie in java.util; a node with a HashMap<Character, Node> or an array is typical.
C++
No trie in the standard library; a node with std::array<Node*, 26> or std::unordered_map is typical.
Step through it
The interactive lab for trie: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.
Implementation in four languages
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
Learn more
Lessons
- Tries: insert, search, prefixes and delete· M22 Tries
Problems, patterns and exercises
- PatternHashing for constant-time lookup· O(n) expected