Tries

The one structure with no java.util equivalent, for the question a hash table cannot answer: what starts with this?

9 min read🧮 Data Structures and Algorithms in Java

A trie is the one common structure with no equivalent in java.util, and it exists for a question a hash table cannot answer: what starts with this?

The question a HashSet cannot answer

Two hundred thousand words. Find every one beginning with payme:

plaintext
###   HashSet, scanning everything :   10.5 ms  (1 found)
###   Trie, walking the prefix     :    0.0 ms  (1 found)
###   same answer? true

The numbers are small; the shape is the point. The HashSet had to look at all two hundred thousand — a hash table can tell you whether a key is present and nothing at all about keys that are similar, so "starts with" degrades to a full scan. Its cost depends on the size of the set.

The trie followed five characters and stopped. Its cost depends on the length of the prefix, not the size of the dictionary, plus the number of matches it then collects.

Put that in an autocomplete firing on every keystroke, for every user, and the difference stops being 10 milliseconds.

What it is

A tree where the path is the key. Each edge is one character; each node is a prefix.

plaintext
        (root)
         /  \
        p    t
       /      \
      a        o
     / \        \
    y   c        p ●
   /     \
  ● (pay)  k ● (pack)
 /
m
|
e ● (payme)

The ● marks a node where a word ends, which is a flag on the node rather than a separate kind of node. That flag is necessary: without it a trie cannot distinguish "pay is a word" from "pay is only a prefix of payment".

java
class Node {
    Map<Character, Node> next = new HashMap<>();
    boolean word;
}
 
void insert(Node n, String w) {
    for (char c : w.toCharArray()) n = n.next.computeIfAbsent(c, k -> new Node());
    n.word = true;
}

Search is the same walk without the computeIfAbsent: follow characters, and if you fall off the tree the word is not there.

The costs, honestly

Time is the good news. Insert and search are O(m) where m is the length of the word — independent of how many words the trie holds. A trie with ten words and one with ten million answer a five-character query in the same number of steps.

Space is the bad news, and it is why tries are rarer than the time complexity suggests. That Node above is an object with a HashMap in it. A map costs at least 48 bytes empty, plus an entry per child, plus a boxed Character key for each. A word of ten characters can cost several hundred bytes of structure — for a word that is ten bytes of text.

The standard mitigations, in the order you would reach for them:

  • An array instead of a map, when the alphabet is small and fixed: Node[] next = new Node[26]. Faster and no boxing, and it wastes 26 slots on every node — which is a win only when nodes are dense.
  • A radix tree (or Patricia trie), which collapses each chain of single-child nodes into one edge holding a whole substring. This is what production implementations use, and it removes most of the waste.
  • Do not use a trie, which is the right answer more often than the structure's fame suggests.

When it is actually worth it

  • Autocomplete and type-ahead. The case it is famous for, and the honest one.
  • Routing tables. Matching the longest prefix is exactly a trie walk — which is what IP routing does, and what an HTTP router does with paths.
  • Dictionary work where you need all words with a prefix, or need to say "no word starts with this" early — a word-game solver, a spell checker.

And when it is not:

  • Exact lookup only. A HashSet is faster and far smaller.
  • Ranges over sortable keys. A TreeMap's subMap already does that, is in the library, and is tested.
  • A small dictionary. Ten thousand words scanned with startsWith is a millisecond, and a millisecond is not worth a hand-written structure.

The one in the library, sort of

Java has no trie, but TreeMap gets you part of the way:

java
TreeMap<String, V> map = ...;
SortedMap<String, V> withPrefix = map.subMap(prefix, prefix + Character.MAX_VALUE);

Because the map is sorted, every key with that prefix sits in one contiguous range, and subMap gives you it in O(log n) plus the number of matches. That is not as good as a trie's O(m) and it is already written, already tested, and needs no new class — which for most applications is the better trade.

Reach for a real trie when the dictionary is large, the queries are many, and you have measured that subMap is not enough.

Under the hood: what a Node actually costs, array versus map

The two implementations in "the costs, honestly" are not close, and the reason is worth pricing out rather than taking on faith.

A HashMap<Character, Node> field is not the map "for free" — it is a pointer to a HashMap object, which itself has a header, a backing Object[] table (16 slots by default, empty), a size field, a load factor, and so on: on a 64-bit JVM with compressed references, an empty HashMap alone is on the order of 48 bytes before it holds a single entry. Every child added is a Map.Entry-like node holding a boxed Character key, a reference to the child Node, a cached hash, and a next-pointer for its bucket — each entry another 30-plus bytes, on top of the child Node object it points to. A ten-character English word can easily cost several hundred bytes of pure structure for ten bytes of text, which is exactly the arithmetic "the costs, honestly" states without deriving.

Node[] next = new Node[26] (an array indexed by c - 'a') removes almost all of that: no HashMap object, no boxed Character, no hash computation, no bucket entries — just 26 contiguous reference slots (8 bytes each with compressed oops, so 208 bytes per node) that are either null or point straight at a child. It trades "no space wasted on absent children" for "no per-child bookkeeping at all", and for a dense alphabet like lowercase English it usually wins outright, because most of a real dictionary's nodes near the root have many children while the sparse leaves — where the array's waste would sting most — are typically a small fraction of the total node count.

A radix tree (Patricia trie) attacks the other source of waste: a long run of single-child nodes (an uncommon suffix like -splaining, spelled out one node per letter) costs one node per character in a plain trie, each with its own (mostly wasted) child structure. Collapsing that run into a single edge holding the substring "-splaining" turns a chain of, say, eleven nodes into one — which is why production prefix structures (IP routing tables are the canonical example) are essentially always radix trees rather than plain tries: the same O(m) time, a fraction of the nodes.

Try it yourself

Price out the two Node designs

A dictionary has 500,000 words, averaging 8 characters, sharing enough prefixes that the trie ends up with 1.2 million distinct nodes in total. Roughly, which costs less in Java: a HashMap-per-node trie, or an array-of-26-per-node trie — and does the answer depend on how many children the average node actually has?

Where the crossover actually sits

At roughly 48+ bytes just for the empty HashMap object per node, before a single entry, the HashMap design is paying a large fixed cost per node regardless of how many children it holds — a leaf with zero or one child still carries the whole map's overhead. The 26-slot array pays a flat 208 bytes per node no matter how many children exist, so it is cheaper exactly when a meaningful fraction of nodes have, say, more than two or three children (common near the root and in a dense-alphabet language), and more wasteful when most nodes are near-leaves with one child each (common far from the root, in long unshared suffixes). For 1.2 million nodes the difference between the two designs is easily tens of megabytes either way — which is also exactly the shape of waste a radix tree is built to remove, by not allocating a node at all for a run of single-child letters.

Misconceptions

  • "A trie is always faster than a hash table." It is faster for prefix queries, which a hash table cannot answer without a full scan — but for exact lookup only, a HashSet is both faster (no character-by-character walk) and dramatically smaller, since it pays for one entry per word rather than one node per character.
  • "The array-of-26 version has no downside." It reserves 26 reference slots on every node whether or not those children exist, so a trie over a sparse or large alphabet (Unicode identifiers, say) wastes far more space per node than the map version does — the array design is a specifically good fit for a small, dense, fixed alphabet, not a universal win.

Sources

  • Donald Knuth, The Art of Computer Programming, Vol. 3 — tries and digital search trees.
  • Robert Sedgewick and Kevin Wayne, Algorithms (4th ed.) — tries, ternary search tries, and the radix-tree (Patricia) variant.
  • Java Object Layout (JOL) documentation and the OpenJDK java.util.HashMap source — for the per-object and per-entry overhead figures this lesson relies on.
Progress is saved on this device and to your account when signed in.