📖 Scenario: Imagine you are building a simple phone contact search feature. You want to quickly check if a contact name exists in your phonebook.
🎯 Goal: Build a Trie data structure and implement a search operation to find if a given contact name exists.
📋 What You'll Learn
Create a TrieNode class with an array for children and a boolean to mark end of word
Create a Trie class with insert and search methods
Insert given contact names into the Trie
Search for a specific contact name using the Trie search method
Print true if the contact exists, otherwise false
💡 Why This Matters
🌍 Real World
Tries are used in search engines, autocomplete features, and spell checkers to quickly find words or prefixes.
💼 Career
Understanding Trie data structure and search operations is important for software engineers working on text processing, search optimization, and coding interviews.
Progress0 / 4 steps
1
Create TrieNode class and initialize root
Create a class called TrieNode with a TrieNode[] children array of size 26 and a boolean isEndOfWord. Then create a class called Trie with a root variable initialized to a new TrieNode.
DSA Java
Hint
Think of TrieNode as a box with 26 slots for letters and a flag to mark if a word ends here.
2
Add insert method to Trie
Inside the Trie class, add a method called insert that takes a String word. Use a for loop with variable i to go through each character of word. For each character, calculate its index as word.charAt(i) - 'a'. If the child at that index is null, create a new TrieNode. Move to that child node. After the loop, mark isEndOfWord as true.
DSA Java
Hint
Insert each letter by creating nodes if missing, then mark the last node as end of word.
3
Add search method to Trie
Inside the Trie class, add a method called search that takes a String word and returns a boolean. Use a for loop with variable i to go through each character of word. Calculate the index as word.charAt(i) - 'a'. If the child at that index is null, return false. Move to that child node. After the loop, return the value of isEndOfWord of the current node.
DSA Java
Hint
Check each letter node exists, if any missing return false, else return if last node marks end of word.
4
Test search method and print result
Create a main method. Inside it, create a Trie object called trie. Insert the words "apple", "app", and "bat" into trie using the insert method. Then print the result of trie.search("app").
DSA Java
Hint
Insert the words first, then search for "app" and print the result.
Practice
(1/5)
1. What does the search operation in a Trie data structure do?
easy
A. Deletes a word from the Trie
B. Checks if a given word exists in the Trie
C. Inserts a new word into the Trie
D. Counts the total words stored in the Trie
Solution
Step 1: Understand the purpose of search in Trie
The search operation is designed to check if a specific word is present in the Trie data structure.
Step 2: Differentiate from other operations
Insertion adds words, deletion removes words, and counting totals words, but search only checks existence.
Final Answer:
Checks if a given word exists in the Trie -> Option B
Quick Check:
Search = Check word presence [OK]
Hint: Search checks presence, not insertion or deletion [OK]
Common Mistakes:
Confusing search with insert operation
Thinking search deletes words
Assuming search counts words
2. Which of the following is the correct method signature for a search operation in a Trie class in Java?
easy
A. public boolean search(String word)
B. public void search(String word)
C. public int search(String word)
D. public String search(String word)
Solution
Step 1: Identify return type for search
Search returns true or false depending on whether the word exists, so return type must be boolean.
Step 2: Check method parameters and return type
Method takes a String word and returns boolean, so signature is public boolean search(String word).
Final Answer:
public boolean search(String word) -> Option A
Quick Check:
Search returns boolean [OK]
Hint: Search returns true/false, so boolean return type [OK]
Common Mistakes:
Using void return type for search
Returning int or String instead of boolean
Incorrect method parameters
3. What will be the output of the following code snippet?
Trie trie = new Trie();
trie.insert("cat");
trie.insert("car");
System.out.println(trie.search("cat"));
System.out.println(trie.search("cap"));
medium
A. true
false
B. false
true
C. true
true
D. false
false
Solution
Step 1: Insert words "cat" and "car" into Trie
Both words are stored in the Trie nodes.
Step 2: Search for "cat" and "cap"
"cat" exists, so search returns true; "cap" does not exist, so search returns false.
Final Answer:
true
false -> Option A
Quick Check:
Search("cat")=true, Search("cap")=false [OK]
Hint: Inserted words return true, missing words return false [OK]
Common Mistakes:
Assuming partial matches return true
Confusing inserted words with similar words
Expecting search to insert missing words
4. Identify the error in the following Trie search method and select the correct fix:
public boolean search(String word) {
TrieNode current = root;
for (int i = 0; i <= word.length(); i++) {
char ch = word.charAt(i);
if (!current.children.containsKey(ch)) {
return false;
}
current = current.children.get(ch);
}
return current.isEndOfWord;
}
medium
A. Return true immediately after first character check
B. Add null check for current before accessing children
C. Use '==' instead of 'containsKey' to check children
D. Change loop condition to i < word.length()
Solution
Step 1: Analyze loop boundary
The loop uses i <= word.length(), which causes index out of bounds error when i equals word.length().
Step 2: Correct loop condition
Change to i < word.length() to iterate valid indices only.
Final Answer:
Change loop condition to i < word.length() -> Option D
Quick Check:
Loop index must be less than length [OK]
Hint: Loop over characters with i < length, not <= length [OK]
Common Mistakes:
Using <= causes index out of bounds
Ignoring null checks on children
Wrong method to check map keys
5. Given a Trie storing the words ["apple", "app", "bat", "bath"], which of the following search queries will return true and why?
Options:
A) search("app")
B) search("bathe")
C) search("bath")
D) search("bat")
hard
A. All queries return true
B. Only "app" and "bat" return true
C. "app", "bat", and "bath" return true
D. Only "bathe" returns true
Solution
Step 1: Check each word in the Trie
Words stored are "apple", "app", "bat", and "bath".
Step 2: Evaluate each search query
"app" exists, so true; "bat" exists, so true; "bath" exists, so true; "bathe" does not exist, so false.
Final Answer:
"app", "bat", and "bath" return true -> Option C
Quick Check:
Search returns true only for stored words [OK]
Hint: Search true only for exact stored words [OK]
Common Mistakes:
Assuming partial or longer words return true
Confusing prefixes with full words
Expecting non-inserted words to return true
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.