Word Search in Trie in DSA Java - Time & Space Complexity
We want to understand how long it takes to find a word in a Trie data structure.
Specifically, how the search time changes as the word length grows.
Analyze the time complexity of the following code snippet.
public boolean search(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (!current.children.containsKey(ch)) {
return false;
}
current = current.children.get(ch);
}
return current.isEndOfWord;
}
This code checks if a given word exists in the Trie by following each character step-by-step.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character of the word.
- How many times: Exactly once per character in the word (word length times).
As the word gets longer, the search checks more characters one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 character checks |
| 100 | About 100 character checks |
| 1000 | About 1000 character checks |
Pattern observation: The number of operations grows directly with the word length.
Time Complexity: O(n)
This means the search time grows linearly with the length of the word you are looking for.
[X] Wrong: "Searching a word in a Trie takes constant time because it's a tree."
[OK] Correct: The search depends on the word length, so it grows linearly, not constant time.
Knowing how Trie search time depends on word length helps you explain efficient prefix searches clearly.
"What if the Trie stored words with only lowercase letters, and we used an array instead of a map for children? How would the time complexity change?"
Practice
Trie data structure in word search problems?Solution
Step 1: Understand Trie structure
A Trie stores characters of words in a tree-like structure where each node represents a character.Step 2: Identify Trie usage in word search
It allows quick prefix-based search, making it efficient to find words starting with given letters.Final Answer:
To efficiently store and search words by their prefixes -> Option DQuick Check:
Trie = prefix search [OK]
- Confusing Trie with sorting data structures
- Thinking Trie stores words as linked lists
- Assuming Trie performs arithmetic on words
Solution
Step 1: Check data types for Trie node
Each node stores a character, an array of 26 children for letters a-z, and a boolean to mark word end.Step 2: Validate options
class TrieNode { char val; TrieNode[] children = new TrieNode[26]; boolean isWord; } matches this structure exactly with char val, TrieNode[] children of size 26, and boolean isWord.Final Answer:
class TrieNode { char val; TrieNode[] children = new TrieNode[26]; boolean isWord; } -> Option AQuick Check:
Correct TrieNode declaration = class TrieNode { char val; TrieNode[] children = new TrieNode[26]; boolean isWord; } [OK]
- Using int or String instead of char for node value
- Using single child instead of array for children
- Using List instead of fixed-size array for children
class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isWord = false;
}
class Trie {
TrieNode root = new TrieNode();
void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int idx = c - 'a';
if (node.children[idx] == null) node.children[idx] = new TrieNode();
node = node.children[idx];
}
node.isWord = true;
}
boolean search(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int idx = c - 'a';
if (node.children[idx] == null) return false;
node = node.children[idx];
}
return node.isWord;
}
}
public class Main {
public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("cat");
trie.insert("car");
System.out.println(trie.search("cat"));
System.out.println(trie.search("cap"));
}
}Solution
Step 1: Insert words "cat" and "car" into Trie
Both words are inserted character by character, marking the last node's isWord as true.Step 2: Search for "cat" and "cap"
"cat" exists with isWord true, so search returns true. "cap" path is missing 'p' node, so returns false.Final Answer:
true false -> Option BQuick Check:
Inserted words found = true, missing word = false [OK]
- Assuming partial prefix returns true
- Not marking isWord correctly on insert
- Confusing character indexing in children array
boolean search(String word) {
TrieNode node = root;
for (int i = 0; i <= word.length(); i++) {
int idx = word.charAt(i) - 'a';
if (node.children[idx] == null) return false;
node = node.children[idx];
}
return node.isWord;
}Solution
Step 1: Analyze loop boundary
The loop runs from i = 0 to i <= word.length(), which causes index out of bounds at last iteration.Step 2: Fix loop condition
Changing condition to i < word.length() prevents accessing invalid index and correctly iterates over characters.Final Answer:
Change loop condition to i < word.length() -> Option CQuick Check:
Loop boundary fix prevents index error [OK]
- Using <= instead of < in loop condition
- Trying to fix by moving idx initialization
- Removing return inside loop causing wrong logic
[ ['o','a','a','n'], ['e','t','a','e'], ['i','h','k','r'], ['i','f','l','v'] ]Words: ["oath", "pea", "eat", "rain"]
Solution
Step 1: Build Trie from given words
Insert all words into a Trie to enable prefix checking during search.Step 2: Perform DFS on board cells
From each cell, explore neighbors recursively, checking if current path matches any prefix in Trie to prune search.Step 3: Collect words found when Trie node marks word end
This approach efficiently finds all words without redundant searches.Final Answer:
Build a Trie from words, then DFS on board checking prefixes in Trie -> Option AQuick Check:
Trie + DFS = efficient word search on board [OK]
- Searching words one by one scanning whole board
- Ignoring prefix pruning causing slow search
- Using sorting and binary search which doesn't fit 2D board
Ready to prove it?
Pass the test and this pattern moves unknown
