Java Data Structure Program · OT75
Implement a Trie (Prefix Tree) in Java
A trie stores words character by character along paths from the root. Words that share a prefix share the same path, so prefix questions are answered by walking that path once.
Problem Statement
Implement a trie with insert(word), search(word), which is true only for complete inserted words, and startsWith(prefix).
Words consist of lowercase English letters.
Input/Output Examples
insert "apple", "app", "apt", "bat"; search("app")OutputtrueExplanation: "app" was inserted as a word.search("ap")OutputfalseExplanation: "ap" is only a prefix.startsWith("ap")OutputtrueExplanation: three words start with "ap".Visual Explanation
- Rootchildrenab
- a → pchildrenpshared by apple, app, apt
- ap →childrenp (end)t (end)app and apt end here
- app → l → echildrene (end)apple
- Done4 words, shared prefixes stored once
search and startsWith walk the same path; the only difference is that search also requires the end-of-word flag on the last node.
Approaches
Both approaches store the same tree. One gives each node an array of 26 children; the other a map.
Approach 1: Array of 26 Children (Recommended)
Idea: each node holds Node[26] and an end flag; the index of a letter is c - 'a'.
- Insert: walk the letters, creating missing nodes, and mark the last node as an end.
- Walk a string: return the last node, or
nullif a letter is missing. searchneeds a node withendset;startsWithneeds any node.
Time: O(L) · Space: O(26 × total letters).
Approach 2: HashMap Children
Idea: each node holds a Map<Character, Node>, created on demand with computeIfAbsent().
- Insert:
n = n.next.computeIfAbsent(c, k -> new Node())for each letter. - Walk with
n.next.get(c). - The same end-flag rule applies.
Time: O(L) · Space: O(total letters).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Array of 26 Children (Recommended)
Very fast lookups, at the cost of 26 slots per node.
public class TrieArray {
// Each node has 26 child slots (a-z) and a flag marking the end of a word
static class Trie {
private static class Node {
Node[] next = new Node[26];
boolean end;
}
private final Node root = new Node();
void insert(String word) {
Node n = root;
for (char c : word.toCharArray()) {
int i = c - 'a';
if (n.next[i] == null) {
n.next[i] = new Node();
}
n = n.next[i];
}
n.end = true;
}
boolean search(String word) {
Node n = walk(word);
return n != null && n.end; // the path exists AND a word ends here
}
boolean startsWith(String prefix) {
return walk(prefix) != null; // the path exists
}
private Node walk(String s) {
Node n = root;
for (char c : s.toCharArray()) {
n = n.next[c - 'a'];
if (n == null) {
return null;
}
}
return n;
}
}
public static void main(String[] args) {
Trie t = new Trie();
for (String w : new String[] {"apple", "app", "apt", "bat"}) {
t.insert(w);
}
System.out.println("search(\"app\") = " + t.search("app"));
System.out.println("search(\"ap\") = " + t.search("ap"));
System.out.println("startsWith(\"ap\") = " + t.startsWith("ap"));
System.out.println("search(\"bat\") = " + t.search("bat"));
System.out.println("startsWith(\"c\") = " + t.startsWith("c"));
}
}
search("app") = true
search("ap") = false
startsWith("ap") = true
search("bat") = true
startsWith("c") = false
Time complexity: O(L) · Space complexity: O(26 × total letters).
Approach 2: HashMap Children
Supports any characters and uses less memory when nodes have few children.
import java.util.HashMap;
import java.util.Map;
public class TrieMap {
// Children stored in a HashMap: works for any character set and saves memory when nodes have few children
static class Trie {
private static class Node {
Map<Character, Node> next = new HashMap<>();
boolean end;
}
private final Node root = new Node();
void insert(String word) {
Node n = root;
for (char c : word.toCharArray()) {
n = n.next.computeIfAbsent(c, k -> new Node());
}
n.end = true;
}
boolean search(String word) {
Node n = walk(word);
return n != null && n.end;
}
boolean startsWith(String prefix) {
return walk(prefix) != null;
}
private Node walk(String s) {
Node n = root;
for (char c : s.toCharArray()) {
n = n.next.get(c);
if (n == null) {
return null;
}
}
return n;
}
}
public static void main(String[] args) {
Trie t = new Trie();
for (String w : new String[] {"apple", "app", "apt", "bat"}) {
t.insert(w);
}
System.out.println("search(\"app\") = " + t.search("app"));
System.out.println("search(\"ap\") = " + t.search("ap"));
System.out.println("startsWith(\"ap\") = " + t.startsWith("ap"));
System.out.println("search(\"bat\") = " + t.search("bat"));
System.out.println("startsWith(\"c\") = " + t.startsWith("c"));
}
}
search("app") = true
search("ap") = false
startsWith("ap") = true
search("bat") = true
startsWith("c") = false
Time complexity: O(L) · Space complexity: O(total letters).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Array of 26 Children | O(L) | O(26 × total letters) |
| HashMap Children | O(L) | O(total letters) |
Here L is the length of the word or prefix. Every operation walks one path of length L, independent of how many words are stored.
Interview Tips and Recommended Approach
- Use an end-of-word flag. Without it, prefixes are indistinguishable from words.
- Reuse the walk helper for both
searchandstartsWith. - Know the applications: autocomplete, spell checking, IP routing and word games.
- Discuss memory. Arrays are fast but large; maps are compact but slower.
Recommended Approach: Array of 26 Children
Why: it gives constant-time child access for lowercase words and the simplest code for insert, search and prefix queries.