What if your keyboard could guess your words instantly, saving you time and effort every time you type?
Why Autocomplete System with Trie in DSA Typescript?
Imagine typing a message on your phone and trying to guess the next word by looking through a huge list of all possible words manually.
You have to scroll through thousands of words every time you want a suggestion.
This manual way is very slow and frustrating.
It wastes time and often leads to mistakes because you might miss the right word or take too long to find it.
A Trie is like a smart tree that stores words by their letters.
It helps quickly find all words that start with the letters you typed so far.
This makes autocomplete fast and easy.
function findWords(prefix: string, words: string[]): string[] {
return words.filter(word => word.startsWith(prefix));
}class TrieNode { children: Map<string, TrieNode> = new Map(); isWord: boolean = false; } class Trie { root = new TrieNode(); insert(word: string) { /*...*/ } autocomplete(prefix: string): string[] { /*...*/ } }
It enables lightning-fast word suggestions as you type, making typing smoother and smarter.
When you search on Google or type a message on your phone, the system suggests words instantly using a Trie-based autocomplete.
Manual search through all words is slow and error-prone.
Trie organizes words by letters for quick prefix search.
Autocomplete with Trie makes typing faster and easier.
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 fast prefix-based searches.Step 2: Connect Trie usage to autocomplete
Autocomplete requires quick lookup of words starting with a given prefix, which Trie supports efficiently.Final Answer:
To efficiently store and search prefixes of words -> Option AQuick Check:
Trie = prefix search [OK]
- Confusing Trie with sorting algorithms
- Thinking Trie encrypts data
- Assuming Trie counts word frequency only
Solution
Step 1: Identify correct data type for children
Children should map characters (string) to TrieNode objects, so Map is correct.Step 2: Check initialization and isEnd flag
Children initialized as new Map(), and isEnd defaults to false indicating not end of word initially.Final Answer:
class TrieNode { children: Map = new Map(); isEnd: boolean = false; } -> Option BQuick Check:
Map for children [OK]
- Using array instead of Map for children
- Using number keys instead of string keys
- Setting isEnd to true by default
autocomplete.getSuggestions('ca')?
class TrieNode {
children: Map = new Map();
isEnd: boolean = false;
}
class AutocompleteSystem {
root: TrieNode = new TrieNode();
insert(word: string) {
let node = this.root;
for (const char of word) {
if (!node.children.has(char)) {
node.children.set(char, new TrieNode());
}
node = node.children.get(char)!;
}
node.isEnd = true;
}
getSuggestions(prefix: string): string[] {
let node = this.root;
for (const char of prefix) {
if (!node.children.has(char)) return [];
node = node.children.get(char)!;
}
const results: string[] = [];
const dfs = (currNode: TrieNode, path: string) => {
if (currNode.isEnd) results.push(path);
for (const [ch, nextNode] of currNode.children) {
dfs(nextNode, path + ch);
}
};
dfs(node, prefix);
return results;
}
}
const autocomplete = new AutocompleteSystem();
autocomplete.insert('cat');
autocomplete.insert('car');
autocomplete.insert('cap');
autocomplete.insert('dog');
console.log(autocomplete.getSuggestions('ca'));Solution
Step 1: Insert words and traverse prefix 'ca'
Words 'cat', 'car', 'cap' are inserted. Searching prefix 'ca' finds node with children 't', 'r', 'p'.Step 2: DFS collects all words starting with 'ca'
DFS from 'ca' node collects 'cat', 'car', and 'cap' as all end nodes under that prefix.Final Answer:
["cat", "car", "cap"] -> Option DQuick Check:
Prefix 'ca' matches cat, car, cap [OK]
- Returning empty list if prefix found
- Returning unrelated words like 'dog'
- Missing one or more words starting with prefix
insert method in a Trie has a bug. What is the bug?
insert(word: string) {
let node = this.root;
for (const char of word) {
if (!node.children.has(char)) {
node.children.set(char, new TrieNode());
}
node = node.children.get(char);
}
node.isEnd = true;
}Solution
Step 1: Identify potential null or undefined access
node.children.get(char) can return undefined if key missing, so TypeScript requires non-null assertion or check.Step 2: Fix by adding non-null assertion operator
Adding '!' after get(char) tells TypeScript the value is not undefined, fixing the bug.Final Answer:
Missing non-null assertion operator (!) when getting child node -> Option AQuick Check:
Use get(char)! to avoid undefined [OK]
- Ignoring TypeScript undefined error
- Changing data structure unnecessarily
- Setting isEnd incorrectly
Solution
Step 1: Understand frequency tracking in Trie
Adding a frequency count to nodes marking word ends allows tracking how often each word was inserted.Step 2: Use frequency to sort suggestions efficiently
During DFS for suggestions, use frequency counts to sort or prioritize words without extra data structures.Final Answer:
Add a frequency count field to each Trie node marking end of word -> Option CQuick Check:
Frequency field in Trie nodes enables sorting [OK]
- Sorting all words on each query (slow)
- Replacing Trie with BST loses prefix efficiency
- Removing isEnd loses word boundary info
Ready to prove it?
Pass the test and this pattern moves unknown
