0
0
DSA C++programming~30 mins

Prefix Search Using Trie in DSA C++ - Build from Scratch

Choose your learning style9 modes available
Prefix Search Using Trie
📖 Scenario: Imagine you are building a simple search feature for a phone contacts app. When a user types the first few letters of a name, the app should quickly show all contacts starting with those letters.
🎯 Goal: Build a Trie data structure to store contact names and implement a prefix search function that returns all contacts starting with a given prefix.
📋 What You'll Learn
Create a TrieNode class with an array of children and a boolean to mark end of word
Create a Trie class with insert and prefix search methods
Insert given contact names into the Trie
Search and print 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 a prefix.
💼 Career
Understanding Tries helps in roles involving search optimization, text processing, and building efficient data retrieval systems.
Progress0 / 4 steps
1
Create TrieNode and Trie classes with insert method
Create a class called TrieNode with a public array children of size 26 initialized to nullptr and a boolean isEndOfWord set to false. Then create a class called Trie with a public root node of type TrieNode* initialized in the constructor. Add a public method insert that takes a string word and inserts it into the Trie.
DSA C++
Hint

Remember to initialize all children pointers to nullptr and set isEndOfWord to false in TrieNode constructor.

2
Insert given contacts into the Trie
Create a vector<string> called contacts with these exact names: "alice", "bob", "alex", "albert", "bobby". Then create a Trie object called trie and insert each contact from contacts into trie using the insert method.
DSA C++
Hint

Use a for loop to insert each contact from the vector into the Trie.

3
Add prefix search method to Trie
Add a public method TrieNode* searchPrefix(string prefix) to the Trie class. This method should return the node where the prefix ends or nullptr if prefix is not found. Use a for loop with variable c to traverse the Trie nodes for each character in prefix.
DSA C++
Hint

Traverse the Trie nodes for each character in the prefix. If any character path is missing, return nullptr. Otherwise, return the last node.

4
Print all contacts starting with a given prefix
Add a helper method void printAllWords(TrieNode* node, string prefix) in Trie that recursively prints all words starting from node by appending characters to prefix. Then in main(), call searchPrefix with "al" and if the returned node is not nullptr, call printAllWords to print all contacts starting with "al".
DSA C++
Hint

Use recursion to explore all children nodes and print words when isEndOfWord is true.