Trie Autocomplete Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Trie Autocomplete runs in O(m) time and O(n*m) space, in Java as in every other language.
- ✓No trie in java.util. The hand-rolled node uses Map<Character, Node> backed by java.util.HashMap, or java.util.TreeMap when you want children already sorted.
- ✓In a hot path a reviewer replaces Map<Character, Node> with Node[] children = new Node[26] or a primitive-keyed map from fastutil (Char2ObjectOpenHashMap) or Eclipse Collections, specifically to kill the boxing.
- ✓The Java trap: Character autoboxing has a cache, and the cache is what hides the bug. Character.valueOf caches 0 through 127 only, so an ASCII benchmark allocates nothing and looks fine, while the first Cyrillic, Greek or accented word allocates a fresh Character object on every single lookup, not just on insert.
- ✓A HashMap-backed node is four objects deep: the Node, its HashMap, the table array, and one HashMap.Node per child, plus a boxed Character key each.
What Trie Autocomplete actually is
Trie Autocomplete in Java: what you actually reach for
Java implementation
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public final class Trie {
private static final class Node {
final Map<Character, Node> children = new TreeMap<>();
boolean isWord;
}
private final Node root = new Node();
public void insert(String word) {
Node cur = root;
for (int i = 0; i < word.length(); i++) {
cur = cur.children.computeIfAbsent(word.charAt(i), k -> new Node());
}
cur.isWord = true;
}
public List<String> complete(String prefix, int limit) {
Node cur = root;
for (int i = 0; i < prefix.length(); i++) {
cur = cur.children.get(prefix.charAt(i));
if (cur == null) {
return List.of();
}
}
List<String> out = new ArrayList<>(limit);
collect(cur, new StringBuilder(prefix), out, limit);
return out;
}
private void collect(Node n, StringBuilder path, List<String> out, int limit) {
if (out.size() >= limit) {
return;
}
if (n.isWord) {
out.add(path.toString());
}
for (Map.Entry<Character, Node> e : n.children.entrySet()) {
path.append(e.getKey().charValue());
collect(e.getValue(), path, out, limit);
path.setLength(path.length() - 1);
}
}
}
Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(m)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Trie Autocomplete?
No trie in java.util. The hand-rolled node uses Map<Character, Node> backed by java.util.HashMap, or java.util.TreeMap when you want children already sorted. Insert is one line with computeIfAbsent. There is a stdlib way to skip the trie entirely: a java.util.TreeSet<String> answers prefix queries through NavigableSet.subSet(prefix, true, prefix + Character.MAX_VALUE, true). The ecosystem trie is org.apache.commons.collections4.trie.PatriciaTrie, whose prefixMap(String) returns a live SortedMap view of one prefix.
What is the most common Java mistake when implementing Trie Autocomplete?
Character autoboxing has a cache, and the cache is what hides the bug. Character.valueOf caches 0 through 127 only, so an ASCII benchmark allocates nothing and looks fine, while the first Cyrillic, Greek or accented word allocates a fresh Character object on every single lookup, not just on insert. On the insert path the box escapes into the map and can never be elided; on the lookup path escape analysis could in principle scalar-replace it, but the box is created at the call site and consumed inside a map method that is rarely inlined deeply enough for that to happen, so in practice you pay for it there too. The second Java-specific trap: String.charAt returns a UTF-16 code unit, so an emoji is stored as two levels of half-surrogates and length() disagrees with codePointCount; walk with codePointAt and charCount if the dictionary is not BMP-only.
How does Trie Autocomplete actually perform in Java?
A HashMap-backed node is four objects deep: the Node, its HashMap, the table array, and one HashMap.Node per child, plus a boxed Character key each. TreeMap trades that for a red-black tree with a Comparable call per level and gives sorted iteration free. JIT warmup dominates microbenchmarks here: computeIfAbsent's lambda is not inlined until the call site is hot, so a first-run measurement of trie build time can be several times the steady-state number. Measure after a few thousand inserts, or use JMH. Time complexity is O(m) and space is O(n*m).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Devin, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.