📖 Scenario: Imagine you are building a simple search suggestion system. You want to store words so that you can quickly find if a word exists or suggest words starting with a prefix.
🎯 Goal: You will build a basic Trie data structure and implement the insert operation to add words to it.
📋 What You'll Learn
Create a TrieNode class with a children map and an isEndOfWord boolean
Create a Trie class with a root node
Implement an insert method in the Trie class to add words
Insert the words "cat", "car", and "dog" into the trie
Print the root node's children keys after insertion
💡 Why This Matters
🌍 Real World
Tries are used in search engines, autocomplete systems, and spell checkers to quickly find words or prefixes.
💼 Career
Understanding tries helps in roles involving text processing, search optimization, and building efficient data retrieval systems.
Progress0 / 4 steps
1
Create TrieNode and Trie classes
Create a class called TrieNode with a children property as a Map<string, TrieNode> and a boolean isEndOfWord initialized to false. Then create a class called Trie with a root property initialized as a new TrieNode.
DSA Typescript
Hint
Use Map to store children nodes. Initialize isEndOfWord to false.
2
Add insert method to Trie
Inside the Trie class, add a method called insert that takes a word string. Initialize a variable current to this.root. This method will add nodes for each character in word if they don't exist.
DSA Typescript
Hint
Loop over each character in word. Check if children has the character. If not, add a new TrieNode. Move current to the child node. After the loop, mark current.isEndOfWord as true.
3
Insert words into the Trie
Create a new Trie instance called trie. Use the insert method to add the words "cat", "car", and "dog" to the trie.
DSA Typescript
Hint
Create a Trie object and call insert with the exact words "cat", "car", and "dog".
4
Print root children keys
Print the keys of the root.children map of the trie instance using console.log. Use Array.from(trie.root.children.keys()) to get the keys as an array.
DSA Typescript
Hint
Use console.log(Array.from(trie.root.children.keys())) to print the first letters of inserted words.
Practice
(1/5)
1. What is the main purpose of the insert operation in a Trie data structure?
easy
A. To add a word character by character into the Trie
B. To delete a word from the Trie
C. To search for a word in the Trie
D. To count the number of words in the Trie
Solution
Step 1: Understand the insert operation
The insert operation adds each character of a word into the Trie one by one, creating new nodes if needed.
To add a word character by character into the Trie -> Option A
Quick Check:
Insert = Add word [OK]
Hint: Insert means adding word step-by-step [OK]
Common Mistakes:
Confusing insert with search or delete
Thinking insert counts words
Assuming insert replaces words
2. Which of the following is the correct TypeScript syntax to start inserting a word into a Trie node named root?
easy
A. let node = root;
B. node = root;
C. const node = root()
D. var node == root;
Solution
Step 1: Understand variable declaration in TypeScript
Using let declares a variable that can be reassigned, suitable for traversal nodes.
Step 2: Check syntax correctness
let node = root; uses correct assignment with let. node = root; misses declaration keyword. const node = root() wrongly calls root as a function. var node == root; uses invalid comparison operator.
Final Answer:
let node = root; -> Option A
Quick Check:
Correct variable declaration = let node = root; [OK]
Hint: Use let for variable assignment in TypeScript [OK]
Common Mistakes:
Missing let or const keyword
Using == instead of = for assignment
Calling node as a function
3. Given the following TypeScript code snippet for inserting the word "cat" into an empty Trie, what will be the printed output after insertion?
class TrieNode {
children: Map = new Map();
isEndOfWord = false;
}
const root = new TrieNode();
function insert(word: string) {
let node = root;
for (const char of word) {
if (!node.children.has(char)) {
node.children.set(char, new TrieNode());
}
node = node.children.get(char)!;
}
node.isEndOfWord = true;
}
insert("cat");
console.log(Array.from(root.children.keys()));
medium
A. ["cat"]
B. ["c", "a", "t"]
C. []
D. ["c"]
Solution
Step 1: Trace insertion of "cat" into Trie
Starting at root, 'c' is not present, so a new node for 'c' is created. Then move to 'c' node, 'a' is added as child, then 't' as child of 'a'.
Step 2: Check root's children keys
Root only has one child node for 'c'. The keys of root.children are ['c'].
Final Answer:
["c"] -> Option D
Quick Check:
Root children keys after insert = ["c"] [OK]
Hint: Root children keys show first letters only [OK]
Common Mistakes:
Expecting all letters at root level
Confusing keys with full words
Ignoring Map keys method
4. Identify the error in the following TypeScript code snippet for inserting a word into a Trie:
function insert(word: string) {
let node = root;
for (const char of word) {
if (!node.children.has(char)) {
node.children.set(char, new TrieNode());
}
node = node.children.get(char);
}
node.isEndOfWord = true;
}
medium
A. Using 'let' instead of 'const' for node
B. Missing parentheses when creating new TrieNode
C. Not checking if node.children.get(char) is undefined
D. Not marking isEndOfWord as false initially
Solution
Step 1: Check new object creation syntax
In TypeScript, when creating a new object, parentheses are required even if no arguments are passed. new TrieNode should be new TrieNode().
Step 2: Verify other parts
Using 'let' for node is fine since node changes. The get method is safe here because we just set the key if missing. isEndOfWord is set at the end, initial value doesn't cause error.
Final Answer:
Missing parentheses when creating new TrieNode -> Option B
Quick Check:
new object needs () [OK]
Hint: Always use () when calling constructors [OK]
Common Mistakes:
Omitting () after new keyword
Confusing let and const for variables
Ignoring possible undefined from get()
5. You want to insert multiple words ["bat", "ball", "batman"] into a Trie. After inserting all, which of the following statements is true about the Trie structure?
hard
A. The node for 'b' has children 'a' and 'm' directly
B. Each word creates a separate branch from root
C. The node for 'b' has children 'a' only, and 'a' has children 't' and 'l'
D. The node for 't' is the end of word for both "bat" and "batman"
Solution
Step 1: Analyze common prefixes in words
Words "bat", "ball", and "batman" share prefix 'b' -> 'a'. From 'a', 't' leads to "bat" and "batman", 'l' leads to "ball".
Step 2: Understand Trie branching
Node 'b' has child 'a'. Node 'a' branches to 't' and 'l'. 'm' is child of 'a'->'t'->'m' for "batman". So 'm' is not direct child of 'b'.
Final Answer:
The node for 'b' has children 'a' only, and 'a' has children 't' and 'l' -> Option C
Quick Check:
Trie branches at shared prefixes [OK]
Hint: Words share nodes for common prefixes only [OK]
Common Mistakes:
Assuming all words start new branches at root
Thinking 'm' is direct child of 'b'
Confusing end of word nodes
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.