Autocomplete System with Trie in DSA Javascript - Time & Space Complexity
We want to know how fast the autocomplete system finds suggestions as we type more letters.
How does the time to get suggestions grow when the input or dictionary size changes?
Analyze the time complexity of the following code snippet.
class TrieNode {
constructor() {
this.children = {};
this.isWord = false;
}
}
class Trie {
constructor() {
this.root = new TrieNode();
}
insert(word) {
let node = this.root;
for (const char of word) {
if (!node.children[char]) node.children[char] = new TrieNode();
node = node.children[char];
}
node.isWord = true;
}
searchPrefix(prefix) {
let node = this.root;
for (const char of prefix) {
if (!node.children[char]) return null;
node = node.children[char];
}
return node;
}
}
This code builds a trie and finds the node matching a prefix to start autocomplete suggestions.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character of the input word or prefix.
- How many times: Once per character in the word or prefix (length m).
- Autocomplete suggestions may involve traversing nodes below the prefix node, but this snippet focuses on prefix search.
Time grows with the length of the prefix typed, not the total number of words stored.
| Input Size (prefix length m) | Approx. Operations |
|---|---|
| 3 | 3 steps to follow nodes |
| 5 | 5 steps to follow nodes |
| 10 | 10 steps to follow nodes |
Pattern observation: The time increases linearly with prefix length, independent of dictionary size.
Time Complexity: O(m)
This means the search time grows only with how many letters you type, not how many words are stored.
[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 letters, so it depends on prefix length, not dictionary size.
Understanding this helps you explain why tries are efficient for autocomplete, showing you know how data structure choice affects speed.
"What if we added a step to collect all words below the prefix node? How would that affect time complexity?"
Practice
Trie in an autocomplete system?Solution
Step 1: Understand the role of Trie in prefix search
A Trie is a tree-like data structure designed to store strings by their prefixes, allowing quick prefix-based searches.Step 2: Relate Trie to autocomplete functionality
Autocomplete needs to find all words starting with a given prefix efficiently, which Trie supports by traversing nodes matching the prefix.Final Answer:
To efficiently store and search prefixes of words -> Option AQuick Check:
Trie = prefix search [OK]
- Confusing Trie with sorting data structure
- Thinking Trie encrypts data
- Assuming Trie counts word frequency only
"cat" into a Trie node in JavaScript?Solution
Step 1: Understand Trie node structure
Each Trie node has a children object mapping characters to child nodes, so to insert 'c', we assign a new TrieNode to node.children['c'].Step 2: Check each option's correctness
node.children['c'] = new TrieNode(); correctly assigns a new TrieNode to the character key. Options B, C, and D do not follow the standard Trie insertion method.Final Answer:
node.children['c'] = new TrieNode(); -> Option BQuick Check:
Insert char by assigning new TrieNode in children map [OK]
- Using array push instead of map assignment
- Assigning string instead of TrieNode
- Calling undefined add method
"app" in a Trie, what will be the output?
const trie = new Trie();
trie.insert("apple");
trie.insert("app");
trie.insert("application");
const results = trie.searchPrefix("app");
console.log(results);Solution
Step 1: Insert words into Trie
Words "apple", "app", and "application" are inserted, so all prefixes starting with "app" exist in the Trie.Step 2: Search for prefix "app"
The searchPrefix method returns all words starting with "app", which includes all three inserted words.Final Answer:
["apple", "app", "application"] -> Option DQuick Check:
All words with prefix "app" returned [OK]
- Expecting only exact matches
- Ignoring shorter word "app" itself
- Assuming empty result if prefix is a word
class TrieNode {
constructor() {
this.children = [];
this.isEnd = false;
}
}
class Trie {
constructor() {
this.root = new TrieNode();
}
insert(word) {
let node = this.root;
for (let char of word) {
if (!node.children[char]) {
node.children[char] = new TrieNode();
}
node = node.children[char];
}
node.isEnd = true;
}
}
const trie = new Trie();
trie.insert("dog");Solution
Step 1: Analyze children data structure
children is initialized as an empty array, but characters are used as keys, which are strings, not numeric indices.Step 2: Identify correct data structure for children
children should be an object (map) to use string keys like 'd', 'o', 'g'. Using array causes undefined behavior and errors.Final Answer:
children should be an object, not an array -> Option AQuick Check:
Use object for children keys [OK]
- Using array for children with string keys
- Setting isEnd incorrectly
- Thinking loop type causes error
Solution
Step 1: Understand requirement for top frequent words
To quickly return top 2 frequent words for any prefix, each node should track frequency info and top words under it.Step 2: Choose data structure modification
Storing frequency counts and maintaining a sorted list of top words at each node allows fast retrieval without full traversal.Final Answer:
Store a frequency count and maintain a sorted list of top words at each node -> Option CQuick Check:
Frequency + top words per node = efficient autocomplete [OK]
- Storing full dictionary at each node wastes memory
- Using arrays for children slows lookup
- Ignoring frequency info for ranking
Ready to prove it?
Pass the test and this pattern moves unknown
