A Trie is a tree-like data structure that stores strings by sharing common prefixes. Each node represents a character, and paths from root to leaves form words.
Click to reveal answer
beginner
Why can't a Hash Map efficiently handle prefix searches on strings?
Hash Maps store keys independently and do not share prefixes. So, searching for all keys with a common prefix requires checking every key, which is slow.
Click to reveal answer
intermediate
How does a Trie improve prefix search compared to a Hash Map?
Trie nodes share prefixes, so searching for all words with a prefix is fast by following the prefix path once, then exploring its subtree.
Click to reveal answer
beginner
What is a real-life example where Trie is better than Hash Map for strings?
Autocomplete in search engines uses Trie to quickly find all words starting with typed letters, which is slow with Hash Maps.
Click to reveal answer
intermediate
What is a limitation of Hash Maps when storing many strings with shared prefixes?
Hash Maps store each string separately, wasting space by repeating prefixes, while Trie stores shared prefixes once, saving memory.
Click to reveal answer
What does each node in a Trie represent?
AA character of a string
BA whole string
CA number
DA hash value
✗ Incorrect
Each node in a Trie represents a single character of a string.
Why is prefix search slow in a Hash Map?
ABecause Hash Maps share prefixes
BBecause Hash Maps do not store keys in order
CBecause Hash Maps store keys as trees
DBecause Hash Maps only store numbers
✗ Incorrect
Hash Maps store keys independently without order or prefix sharing, making prefix search slow.
Which data structure is best for autocomplete features?
ATrie
BHash Map
CStack
DQueue
✗ Incorrect
Trie efficiently supports prefix search, making it ideal for autocomplete.
How does Trie save memory compared to Hash Map when storing many strings?
ABy compressing strings into numbers
BBy storing strings as hash codes
CBy sharing common prefixes in nodes
DBy storing strings in arrays
✗ Incorrect
Trie nodes share prefixes, so common parts are stored once, saving memory.
Which operation is faster in Trie than in Hash Map?
AFinding a string by exact match
BDeleting a node
CInserting a number
DFinding all strings with a given prefix
✗ Incorrect
Trie is designed to quickly find all strings sharing a prefix.
Explain why Trie is used instead of Hash Map for prefix-based string searches.
Think about how strings with common beginnings are stored and searched.
You got /4 concepts.
Describe a real-world scenario where Trie outperforms Hash Map for string operations.
Consider typing suggestions in search engines or phone contacts.
You got /4 concepts.
Practice
(1/5)
1. Why do we use a Trie data structure instead of a Hash Map for storing a large set of strings?
easy
A. Because Trie uses less memory than Hash Map always
B. Because Trie supports efficient prefix search which Hash Map cannot do easily
C. Because Hash Map cannot store strings as keys
D. Because Trie is faster for all types of lookups
Solution
Step 1: Understand Trie and Hash Map capabilities
Trie stores strings in a tree form allowing prefix-based queries efficiently. Hash Map stores keys but does not support prefix search directly.
Step 2: Compare prefix search ability
Hash Map can check full keys but cannot find all keys with a given prefix efficiently. Trie can find all keys sharing a prefix quickly.
Final Answer:
Because Trie supports efficient prefix search which Hash Map cannot do easily -> Option B
Quick Check:
Prefix search = Trie advantage [OK]
Hint: Trie is for prefix search; Hash Map is not [OK]
Common Mistakes:
Thinking Hash Map can do prefix search efficiently
Assuming Trie always uses less memory
Believing Hash Map cannot store string keys
2. Which of the following is the correct way to initialize a Trie node in Python?
easy
A. node = set()
B. node = []
C. node = {'children': {}, 'is_end': False}
D. node = ''
Solution
Step 1: Identify Trie node structure
A Trie node typically has a dictionary for children and a boolean to mark end of word.
Step 2: Match with options
node = {'children': {}, 'is_end': False} correctly uses a dictionary for children and a boolean flag. Others do not represent Trie node structure.
Final Answer:
node = {'children': {}, 'is_end': False} -> Option C
Quick Check:
Trie node = dict + bool [OK]
Hint: Trie node needs children dict and end flag [OK]
Common Mistakes:
Using list or set instead of dictionary for children
Not including end-of-word marker
Using empty string as node
3. What will be the output of the following code snippet?
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end = True
def search(self, word):
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_end
trie = Trie()
trie.insert('cat')
trie.insert('car')
print(trie.search('cat'))
print(trie.search('ca'))
print(trie.search('car'))
medium
A. True\nFalse\nTrue
B. True\nTrue\nTrue
C. False\nFalse\nFalse
D. True\nFalse\nFalse
Solution
Step 1: Insert words 'cat' and 'car'
Both words are inserted character by character, marking end of word at last character.
Step 2: Search for 'cat', 'ca', and 'car'
'cat' and 'car' exist fully with end marked True, so search returns True. 'ca' is prefix but not end of word, so returns False.
Final Answer:
True\nFalse\nTrue -> Option A
Quick Check:
Search full word only returns true [OK]
Hint: Search returns true only if full word inserted [OK]
Common Mistakes:
Assuming prefix search returns true
Confusing is_end flag usage
Not updating node during insert
4. The following code tries to insert words into a Trie but has a bug. What is the bug?
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for char in word:
if char in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end = True
medium
A. It does not initialize the root node
B. It never marks the end of word
C. It uses list instead of dictionary for children
D. It overwrites existing child nodes instead of checking if they exist
Solution
Step 1: Analyze insert method condition
The code checks if char is in children, then overwrites with new TrieNode, which erases existing nodes.
Step 2: Identify correct logic
It should add new TrieNode only if char NOT in children, to avoid overwriting existing nodes.
Final Answer:
It overwrites existing child nodes instead of checking if they exist -> Option D
Quick Check:
Insert overwrites nodes = bug [OK]
Hint: Add node only if child missing, not if present [OK]
Common Mistakes:
Confusing if condition logic
Forgetting to mark end of word
Not initializing root node
5. You want to find all words in a dictionary that start with the prefix 'pre'. Why is a Trie better than a Hash Map for this task, and how would you implement the prefix search?
hard
A. Trie stores words in a tree allowing prefix traversal; implement by walking nodes for prefix then collecting all descendants
B. Hash Map stores keys with prefix indexing; implement by filtering keys starting with prefix
C. Trie hashes prefixes for quick lookup; implement by hashing prefix and returning matches
D. Hash Map stores words sorted; implement by binary search on keys
Solution
Step 1: Understand prefix search in Trie vs Hash Map
Trie organizes words by characters in a tree, enabling direct traversal to prefix node. Hash Map keys are unordered, so prefix search requires scanning all keys.
Step 2: Describe prefix search implementation in Trie
Traverse Trie nodes for each prefix character, then recursively collect all words from that node's descendants.
Final Answer:
Trie stores words in a tree allowing prefix traversal; implement by walking nodes for prefix then collecting all descendants -> Option A