java
51 lines · 8 steps
Building a trie for autocomplete in Java
A prefix tree that stores words character by character and walks its branches to suggest completions.
Explained by
highlit
1import java.util.ArrayList;
2import java.util.HashMap;
3import java.util.List;
4import java.util.Map;
5
6public class AutocompleteTrie {
7
8 private static final class Node {
9 final Map<Character, Node> children = new HashMap<>();
10 boolean isWord;
11 int frequency;
12 }
13
14 private final Node root = new Node();
15
16 public void insert(String word) {
17 Node node = root;
18 for (char c : word.toCharArray()) {
19 node = node.children.computeIfAbsent(c, k -> new Node());
20 }
21 node.isWord = true;
22 node.frequency++;
23 }
24
25 public List<String> suggest(String prefix, int limit) {
26 List<String> results = new ArrayList<>();
27 Node node = root;
28 for (char c : prefix.toCharArray()) {
29 node = node.children.get(c);
30 if (node == null) {
31 return results;
32 }
33 }
34 collect(node, new StringBuilder(prefix), results, limit);
35 return results;
36 }
37
38 private void collect(Node node, StringBuilder path, List<String> out, int limit) {
39 if (out.size() >= limit) {
40 return;
41 }
42 if (node.isWord) {
43 out.add(path.toString());
44 }
45 for (Map.Entry<Character, Node> entry : node.children.entrySet()) {
46 path.append(entry.getKey());
47 collect(entry.getValue(), path, out, limit);
48 path.deleteCharAt(path.length() - 1);
49 }
50 }
51}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A trie shares common prefixes across words so lookups depend on prefix length, not the size of the dictionary.
- 2Backtracking with a mutable StringBuilder rebuilds each word's path while reusing one buffer across the whole traversal.
- 3Passing a limit down the recursion lets you stop collecting suggestions as soon as you have enough.
Related explainers
java
public interface GitHubClient { @GetExchange("/users/{username}") GitHubUser getUser(@PathVariable String username);
Declarative HTTP clients in Spring
http-client
declarative-api
proxy
Intermediate
8 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
java
@RestController @RequestMapping("/api/products") public class ProductSearchController {
Binding collection query params in Spring
rest-api
query-parameters
dependency-injection
Intermediate
6 steps
java
import java.util.ArrayDeque; import java.util.Deque; import java.util.Map;
Evaluating math expressions with two stacks
stacks
parsing
operator-precedence
Intermediate
9 steps
java
@Entity @Table(name = "orders") @SQLDelete(sql = "UPDATE orders SET deleted = true, deleted_at = now() WHERE id = ?") @Where(clause = "deleted = false")
Soft deletes with Hibernate in Spring
soft-delete
jpa
hibernate
Intermediate
9 steps
java
@GetMapping("/files/{id}") public ResponseEntity<StreamingResponseBody> download( @PathVariable String id, @RequestHeader(value = HttpHeaders.RANGE, required = false) String rangeHeader) throws IOException {
HTTP range requests in Spring
http-range
streaming
file-io
Advanced
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-trie-for-autocomplete-in-java-explained-java-251c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.