0
0
DSA C++programming~30 mins

Why Trie Exists and What Hash Map Cannot Do for Strings in DSA C++ - See It Work

Choose your learning style9 modes available
Why Trie Exists and What Hash Map Cannot Do for Strings
📖 Scenario: Imagine you are building a phone directory app that stores many names. You want to quickly find all names that start with a certain prefix, like "AL" to find "ALICE", "ALBERT", and "ALFRED".Using a hash map (dictionary) can find exact names fast, but it cannot easily find all names starting with a prefix. This is where a Trie (prefix tree) helps.
🎯 Goal: Build a simple Trie data structure to store a list of names and find all names starting with a given prefix.This will show why Trie is useful and what hash maps cannot do easily with strings.
📋 What You'll Learn
Create a list of names as strings
Create a prefix string to search
Build a Trie to insert all names
Search the Trie for all names starting with the prefix
Print the list of names found with the prefix
💡 Why This Matters
🌍 Real World
Tries are used in search engines, autocomplete, spell checkers, and dictionaries to quickly find words by prefix.
💼 Career
Understanding Tries helps in software roles involving text processing, search optimization, and building efficient data retrieval systems.
Progress0 / 4 steps
1
Create the list of names
Create a std::vector<std::string> called names with these exact entries: "ALICE", "ALBERT", "ALFRED", "BOB", "BOBBY"
DSA C++
Hint

Use std::vector<std::string> and initialize it with the exact names inside curly braces.

2
Create the prefix string to search
Create a std::string variable called prefix and set it to "AL"
DSA C++
Hint

Use std::string prefix = "AL"; to create the prefix variable.

3
Build a simple Trie and insert all names
Define a struct TrieNode with a std::vector<TrieNode*> called children of size 26 initialized to nullptr, and a bool called isEndOfWord initialized to false. Then create a class Trie with a TrieNode* root initialized in the constructor. Add a public method void insert(const std::string &word) that inserts each character of word into the Trie. Insert all names from names into the Trie using a for loop.
DSA C++
Hint

Remember to create 26 children for each letter A-Z and mark the end of word.

Insert each name by looping over its characters and creating nodes if missing.

4
Search the Trie for names starting with the prefix and print them
Add a private helper method void dfs(TrieNode* node, std::string ¤t, std::vector<std::string> &result) in Trie that does a depth-first search to collect all words starting from node. Add a public method std::vector<std::string> startsWith(const std::string &prefix) that finds the node matching the prefix and calls dfs to collect all words starting with it. In main(), call startsWith(prefix) and print each found name on its own line.
DSA C++
Hint

Use a depth-first search to collect all words starting from the prefix node.

Print each found name on its own line.