Video in progress
A search box needs autocomplete: finding words by prefix quickly. How does a Trie help, and when is it overkill?
A trie stores each letter as a tree node, so finding a prefix depends on the prefix length, not on the number of words: O(L). But it eats a lot of memory; in many cases a sorted list with binary search is enough.
📖 Answer
class Trie {
private static class Node {
final Map<Character, Node> next = new HashMap<>();
boolean word;
}
private final Node root = new Node();
void insert(String w) {
Node n = root;
for (char c : w.toCharArray()) n = n.next.computeIfAbsent(c, k -> new Node());
n.word = true;
}
List<String> withPrefix(String p, int limit) {
Node n = root;
for (char c : p.toCharArray()) {
n = n.next.get(c);
if (n == null) return List.of();
}
List<String> out = new ArrayList<>();
collect(n, new StringBuilder(p), out, limit);
return out;
}
private void collect(Node n, StringBuilder sb, List<String> out, int limit) {
if (out.size() >= limit) return;
if (n.word) out.add(sb.toString());
for (var e : n.next.entrySet()) {
sb.append(e.getKey());
collect(e.getValue(), sb, out, limit);
sb.deleteCharAt(sb.length() - 1);
}
}
}
Memory is a serious issue. Each node has a HashMap, which is a few hundred bytes. A dictionary of a hundred thousand words easily reaches hundreds of megabytes. If it's only lowercase Latin letters, a Node[26] array is faster, but if the trie is sparse it still wastes space.
A simpler alternative: keep the words in a sorted String[], find where the prefix starts with Arrays.binarySearch, and read the following elements until the prefix stops matching. O(log n + k), with almost no extra memory. TreeMap.subMap(prefix, prefix + Character.MAX_VALUE) is the same idea.
When a trie pays off: very many queries, words added dynamically, or when you need extra data on each node (popularity, top-k). In real autocomplete systems, though, Elasticsearch's completion suggester is often used.
Sign up to mark studied questions and save your progress.