Prefix Search Using Trie in DSA Java - Time & Space Complexity
We want to understand how fast we can find words that start with a given prefix using a Trie.
How does the search time change as the prefix length or number of words grows?
Analyze the time complexity of the following code snippet.
class TrieNode {
TrieNode[] children = new TrieNode[26];
boolean isWord = false;
}
boolean startsWith(TrieNode root, String prefix) {
TrieNode node = root;
for (char c : prefix.toCharArray()) {
if (node.children[c - 'a'] == null) return false;
node = node.children[c - 'a'];
}
return true;
}
This code checks if any word in the Trie starts with the given prefix by following nodes for each prefix character.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over each character in the prefix string.
- How many times: Exactly once per character in the prefix (length m).
The time grows directly with the length of the prefix we search for.
| Input Size (prefix length m) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows linearly with prefix length, not with total words stored.
Time Complexity: O(m)
This means the search time depends only on how long the prefix is, not on how many words are in the Trie.
[X] Wrong: "The search time depends on the total number of words stored in the Trie."
[OK] Correct: The search only follows nodes for the prefix characters, so it depends on prefix length, not total words.
Knowing how prefix search time depends on prefix length helps you explain why Tries are efficient for autocomplete and dictionary lookups.
"What if we changed the Trie to store words with uppercase letters and digits? How would the time complexity change?"
Practice
Trie data structure in prefix search?Solution
Step 1: Understand what prefix search means
Prefix search means finding all words that start with a certain beginning sequence of letters.Step 2: Understand Trie's role in prefix search
A Trie stores words in a tree where each node represents a letter, making it easy to find all words sharing the same prefix by traversing the tree.Final Answer:
To efficiently find all words that start with a given prefix -> Option AQuick Check:
Prefix search = efficient word lookup [OK]
- Confusing Trie with sorting data structures
- Thinking Trie is for arithmetic operations
- Assuming Trie stores numbers only
Solution
Step 1: Identify the correct type for children nodes
Each child should be a reference to another TrieNode, so the array type must be TrieNode[].Step 2: Check the other parts of the class
Boolean isEndOfWord marks if the node ends a word, which is correct in class TrieNode { TrieNode[] children = new TrieNode[26]; boolean isEndOfWord; }.Final Answer:
class TrieNode { TrieNode[] children = new TrieNode[26]; boolean isEndOfWord; } -> Option DQuick Check:
Children are TrieNode references [OK]
- Using int or char arrays instead of TrieNode array
- Using String array for children
- Forgetting to mark end of word
Trie trie = new Trie();
trie.insert("cat");
trie.insert("car");
trie.insert("dog");
System.out.println(trie.startsWith("ca"));
System.out.println(trie.startsWith("do"));
System.out.println(trie.startsWith("bat"));Solution
Step 1: Insert words into the Trie
Words "cat", "car", and "dog" are inserted, so prefixes "ca" and "do" exist in the Trie.Step 2: Check startsWith results
startsWith("ca") returns true because "cat" and "car" start with "ca".
startsWith("do") returns true because "dog" starts with "do".
startsWith("bat") returns false because no word starts with "bat".Final Answer:
true true false -> Option AQuick Check:
Prefix "ca" and "do" found, "bat" not found [OK]
- Assuming startsWith returns false if word not complete
- Confusing startsWith with search for whole word
- Mixing up true/false outputs
public boolean startsWith(String prefix) {
TrieNode node = root;
for (int i = 0; i <= prefix.length(); i++) {
char c = prefix.charAt(i);
if (node.children[c - 'a'] == null) return false;
node = node.children[c - 'a'];
}
return true;
}Solution
Step 1: Analyze the for-loop condition
The loop runs from i = 0 to i <= prefix.length(), which means it tries to access prefix.charAt(prefix.length()), causing an IndexOutOfBoundsException.Step 2: Correct the loop condition
The loop should run while i < prefix.length() to access valid characters only.Final Answer:
The loop condition should be < instead of <= to avoid IndexOutOfBoundsException -> Option BQuick Check:
Loop index must be less than length [OK]
- Using <= instead of < in loop condition
- Incorrect character arithmetic
- Returning wrong boolean at the end
"app". Which approach correctly retrieves all such words?Solution
Step 1: Locate the prefix node in the Trie
Traverse the Trie following letters 'a', 'p', 'p' to reach the node representing the last 'p' in "app".Step 2: Collect all words below this node
Perform a depth-first search (DFS) from this node to find all complete words that start with "app".Final Answer:
Traverse the Trie to the node representing 'p' in "app", then perform a depth-first search collecting all words below -> Option CQuick Check:
Prefix node + DFS = all matching words [OK]
- Checking all words instead of using Trie structure
- Using hash map instead of Trie traversal
- Confusing insertion with search
Ready to prove it?
Pass the test and this pattern moves unknown
