Challenge - 5 Problems
Prefix Matching Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Prefix Search Using Trie
What is the output of the following Rust code that inserts words into a Trie and searches for words with prefix "app"?
DSA Rust
struct TrieNode {
children: std::collections::HashMap<char, Box<TrieNode>>,
is_end: bool,
}
impl TrieNode {
fn new() -> Self {
TrieNode {
children: std::collections::HashMap::new(),
is_end: false,
}
}
fn insert(&mut self, word: &str) {
let mut node = self;
for ch in word.chars() {
node = node.children.entry(ch).or_insert(Box::new(TrieNode::new())).as_mut();
}
node.is_end = true;
}
fn starts_with(&self, prefix: &str) -> Vec<String> {
fn dfs(node: &TrieNode, prefix: &str, path: &mut String, results: &mut Vec<String>) {
if node.is_end {
results.push(path.clone());
}
for (ch, child) in &node.children {
path.push(*ch);
dfs(child, prefix, path, results);
path.pop();
}
}
let mut node = self;
for ch in prefix.chars() {
if let Some(next_node) = node.children.get(&ch) {
node = next_node;
} else {
return vec![];
}
}
let mut results = Vec::new();
let mut path = prefix.to_string();
dfs(node, prefix, &mut path, &mut results);
results
}
}
fn main() {
let mut trie = TrieNode::new();
trie.insert("apple");
trie.insert("app");
trie.insert("application");
trie.insert("bat");
let result = trie.starts_with("app");
println!("{:?}", result);
}Attempts:
2 left
💡 Hint
Think about all words inserted that start with "app" including the prefix itself.
✗ Incorrect
The Trie stores all inserted words. The prefix search returns all words starting with "app" including "app" itself, "apple", and "application".
🧠 Conceptual
intermediateWhy Use Trie Over Hash Map for Prefix Matching?
Which of the following is the main advantage of using a Trie over a Hash Map for prefix matching?
Attempts:
2 left
💡 Hint
Think about how prefix search works in both data structures.
✗ Incorrect
Trie stores characters in a tree structure allowing quick traversal for prefixes, while Hash Map requires checking all keys or storing all prefixes explicitly.
❓ Predict Output
advancedOutput of Prefix Search Using Hash Map with All Prefixes
What is the output of this Rust code that stores all prefixes in a Hash Map and queries for prefix "app"?
DSA Rust
use std::collections::HashMap;
fn main() {
let words = vec!["apple", "app", "application", "bat"];
let mut prefix_map: HashMap<String, Vec<String>> = HashMap::new();
for word in &words {
for i in 1..=word.len() {
let prefix = &word[..i];
prefix_map.entry(prefix.to_string()).or_default().push(word.to_string());
}
}
let result = prefix_map.get("app");
match result {
Some(list) => println!("{:?}", list),
None => println!("[]"),
}
}Attempts:
2 left
💡 Hint
All words starting with "app" are stored under that prefix key.
✗ Incorrect
The code stores every prefix of each word as a key in the Hash Map with a list of words that have that prefix. Querying "app" returns all words starting with "app".
🔧 Debug
advancedIdentify the Bug in Trie Prefix Search
What error will this Rust Trie prefix search code produce when searching for prefix "cat" after inserting "car" and "cart"?
DSA Rust
struct TrieNode {
children: std::collections::HashMap<char, Box<TrieNode>>,
is_end: bool,
}
impl TrieNode {
fn new() -> Self {
TrieNode {
children: std::collections::HashMap::new(),
is_end: false,
}
}
fn insert(&mut self, word: &str) {
let mut node = self;
for ch in word.chars() {
node = node.children.entry(ch).or_insert(Box::new(TrieNode::new())).as_mut();
}
node.is_end = true;
}
fn starts_with(&self, prefix: &str) -> Vec<String> {
let mut node = self;
for ch in prefix.chars() {
node = node.children.get(&ch).unwrap();
}
vec![prefix.to_string()]
}
}
fn main() {
let mut trie = TrieNode::new();
trie.insert("car");
trie.insert("cart");
let result = trie.starts_with("cat");
println!("{:?}", result);
}Attempts:
2 left
💡 Hint
Check what happens when prefix characters are not found in children.
✗ Incorrect
The code uses unwrap() on an Option that is None when the prefix character 't' is not found under 'ca'. This causes a runtime panic.
🧠 Conceptual
expertMemory Efficiency Comparison: Trie vs Hash Map for Large Prefix Sets
Which statement best describes memory usage when storing a large dictionary of words for prefix matching using Trie vs Hash Map storing all prefixes explicitly?
Attempts:
2 left
💡 Hint
Consider how common prefixes are stored in Trie versus Hash Map.
✗ Incorrect
Trie shares nodes for common prefixes, reducing memory usage, while Hash Map stores each prefix as a separate key, increasing memory usage.
