Prefix Search Using Trie in DSA Javascript - 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 or dictionary grows?
Analyze the time complexity of the following code snippet.
class TrieNode {
constructor() {
this.children = {};
this.isEnd = false;
}
}
function prefixSearch(root, prefix) {
let node = root;
for (const char of prefix) {
if (!node.children[char]) return false;
node = node.children[char];
}
return true;
}
This code checks if any word in the Trie starts with the given prefix by walking down the Trie nodes.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character of the prefix.
- How many times: Exactly once per character in the prefix (length m).
As the prefix gets longer, the search takes more steps, one per character.
| Input Size (prefix length m) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: The time grows linearly with the prefix length.
Time Complexity: O(m)
This means the search time depends only on the prefix length, not the number of words stored.
[X] Wrong: "The search time depends on the total number of words in the Trie."
[OK] Correct: The search only follows the prefix characters, so it depends on prefix length, not total words.
Knowing how prefix search scales helps you explain efficient word lookup in real apps like autocomplete.
"What if we changed the prefix search to return all words starting with the prefix? How would the time complexity change?"