Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Trie Autocomplete Implementation in Java

14 min readintermediate
Website QA and SEO audits

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

A trie stores a set of strings as a tree where each edge carries one character and every node is the shared prefix of everything beneath it. Walking m characters lands you on the subtree of all completions, so prefix lookup costs O(m) regardless of dictionary size; enumerating k suggestions then costs O(k) plus the length of what you emit. Engineers reach for it for search-box typeahead, command palettes, IP/route tables and spell correction: anywhere the query is a prefix and the answer set must be produced per keystroke. If the dictionary is static and read-only, a sorted array plus binary search is usually smaller and faster.

Trie Autocomplete in Java: what you actually reach for

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.

Java implementation

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. Result building uses a single StringBuilder with setLength(len - 1) to backtrack, never string concatenation inside recursion. The node class is a private static final nested class with package-private fields, and the public method returns List<String>, with List.of() for the empty case.
java
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 Free

The Java-specific 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. 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.

Performance in Java, beyond the O(m)

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. The asymptotic cost is the same in every language, O(m) time and O(n*m) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Trie Autocomplete between languages.

Real-World Applications

Trie Autocomplete applies wherever its problem shape appears in your own code. In Java, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Trie Autocomplete helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Trie Autocomplete appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Trie Autocomplete over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Trie Autocomplete to build pattern recognition. In Java, demonstrate proficiency with generics and streams API to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Java code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Before paying for Devin, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.