0
0
DSA C++programming~30 mins

Word Search in Trie in DSA C++ - Build from Scratch

Choose your learning style9 modes available
Word Search in Trie
📖 Scenario: Imagine you have a small dictionary of words and you want to quickly check if a word exists in it. A Trie is a tree-like data structure that helps you do this efficiently.In this project, you will build a simple Trie with a few words and then search for a specific word in it.
🎯 Goal: You will create a Trie with given words, set up a search word, write the search logic to check if the word exists in the Trie, and finally print the result.
📋 What You'll Learn
Create a TrieNode class with an array of 26 children pointers and a boolean to mark end of word
Insert given words into the Trie
Create a string variable for the word to search
Write a function to search the word in the Trie
Print 'Found' if the word exists, otherwise print 'Not Found'
💡 Why This Matters
🌍 Real World
Tries are used in autocomplete systems, spell checkers, and IP routing to quickly find words or prefixes.
💼 Career
Understanding Tries helps in software engineering roles involving text processing, search engines, and efficient data retrieval.
Progress0 / 4 steps
1
Create TrieNode class and insert words
Create a class called TrieNode with a public boolean isEndOfWord initialized to false and an array of 26 TrieNode* pointers called children initialized to nullptr. Then create a class called Trie with a public TrieNode* called root initialized to a new TrieNode. Finally, write a public method insert in Trie that takes a const string& called word and inserts it into the Trie by creating nodes for each character.
DSA C++
Hint

Remember to initialize all children pointers to nullptr in the TrieNode constructor.

In the insert method, create new nodes only if the child pointer is nullptr.

2
Set the word to search
Create a string variable called searchWord and set it to "cat".
DSA C++
Hint

Just create a string variable named searchWord and assign it the value "cat".

3
Write search function in Trie
Add a public method bool search(const string& word) in the Trie class that returns true if the word exists in the Trie and false otherwise. Use a loop to traverse the Trie nodes for each character. Return node->isEndOfWord at the end.
DSA C++
Hint

Traverse the Trie nodes for each character in the word.

If any character node is missing, return false.

At the end, return node->isEndOfWord to confirm the word exists.

4
Insert words, search and print result
Create a Trie object called trie. Insert the words "cat", "car", and "dog" into trie using the insert method. Then use the search method to check if searchWord exists in the Trie. Print "Found" if it exists, otherwise print "Not Found".
DSA C++
Hint

Create a Trie object named trie.

Insert the words "cat", "car", and "dog" using trie.insert().

Use trie.search(searchWord) to check if the word exists.

Print "Found" if true, otherwise "Not Found".