📖 Scenario: You are building a simple search feature for a phone contacts app. When a user types some letters, the app should quickly find all contact names that start with those letters.
🎯 Goal: Build a Trie data structure to store contact names and implement a prefix search method to find all contacts starting with a given prefix.
📋 What You'll Learn
Create a TrieNode class with children and end-of-word marker
Create a Trie class with insert and prefix search methods
Insert given contact names into the Trie
Search and return all contacts starting with a given prefix
💡 Why This Matters
🌍 Real World
Tries are used in search engines, autocomplete features, and spell checkers to quickly find words starting with certain letters.
💼 Career
Understanding Tries helps in building efficient search features and is a common topic in coding interviews for software engineering roles.
Progress0 / 4 steps
1
Create TrieNode class and initialize root
Create a class called TrieNode with a Map children and a boolean isEndOfWord. Then create a class called Trie with a TrieNode root initialized in its constructor.
DSA Java
Hint
Think of TrieNode as a box holding links to next letters and a flag if a word ends here. The Trie has a root node to start all searches.
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 ch to iterate over each character of word. Insert each character into the Trie by creating new TrieNode if needed. Mark the last node's isEndOfWord as true.
DSA Java
Hint
Loop through each letter. If the letter is not in children, add a new node. Move current to that child. After loop, mark end of word.
3
Add prefix search method to Trie
Inside the Trie class, add a method called searchPrefix that takes a String prefix and returns a List of all words starting with that prefix. Use a helper method collectAllWords that recursively collects words from a given TrieNode. Use a for loop with variable ch to traverse the prefix nodes.
DSA Java
Hint
First find the node matching the prefix. Then recursively collect all words below it by adding letters and backtracking.
4
Test prefix search and print results
Create a main method in a Solution class. Create a Trie object called trie. Insert these exact contact names: "Alice", "Alina", "Bob", "Bobby", "Bonnie". Then call searchPrefix on "Bo" and print each result on its own line using a for loop with variable name.
DSA Java
Hint
Insert the exact names, then search prefix "Bo" and print each found name on its own line.
Practice
(1/5)
1. What is the main purpose of using a Trie data structure in prefix search?
easy
A. To efficiently find all words that start with a given prefix
B. To sort words alphabetically
C. To store numbers in sorted order
D. To perform arithmetic operations quickly
Solution
Step 1: Understand what prefix search means
Prefix search means finding all words that start with a certain beginning sequence of letters.
Step 2: Understand Trie's role in prefix search
A Trie stores words in a tree where each node represents a letter, making it easy to find all words sharing the same prefix by traversing the tree.
Final Answer:
To efficiently find all words that start with a given prefix -> Option A
Quick Check:
Prefix search = efficient word lookup [OK]
Hint: Trie nodes represent letters for fast prefix lookup [OK]
Common Mistakes:
Confusing Trie with sorting data structures
Thinking Trie is for arithmetic operations
Assuming Trie stores numbers only
2. Which of the following is the correct way to declare a Trie node class in Java?
easy
A. class TrieNode { int[] children = new int[26]; boolean isEndOfWord; }
B. class TrieNode { char[] children = new char[26]; boolean isEndOfWord; }
C. class TrieNode { String[] children = new String[26]; boolean isEndOfWord; }
D. class TrieNode { TrieNode[] children = new TrieNode[26]; boolean isEndOfWord; }
Solution
Step 1: Identify the correct type for children nodes
Each child should be a reference to another TrieNode, so the array type must be TrieNode[].
Step 2: Check the other parts of the class
Boolean isEndOfWord marks if the node ends a word, which is correct in class TrieNode { TrieNode[] children = new TrieNode[26]; boolean isEndOfWord; }.
Final Answer:
class TrieNode { TrieNode[] children = new TrieNode[26]; boolean isEndOfWord; } -> Option D
Quick Check:
Children are TrieNode references [OK]
Hint: Children array holds TrieNode references, not primitives [OK]
Common Mistakes:
Using int or char arrays instead of TrieNode array
Using String array for children
Forgetting to mark end of word
3. Given the following code snippet, what will be the output?
Words "cat", "car", and "dog" are inserted, so prefixes "ca" and "do" exist in the Trie.
Step 2: Check startsWith results
startsWith("ca") returns true because "cat" and "car" start with "ca". startsWith("do") returns true because "dog" starts with "do". startsWith("bat") returns false because no word starts with "bat".