Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to insert a word into the Trie.
DSA Rust
fn insert(&mut self, word: &str) {
let mut node = &mut self.root;
for ch in word.chars() {
node = node.children.entry(ch).or_insert_with(|| TrieNode::new());
}
node.is_word = [1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Setting is_word to false instead of true.
Forgetting to mark the end of the word.
✗ Incorrect
Marking the end of a word in the Trie requires setting is_word to true.
2fill in blank
mediumComplete the code to check if a node has a child for a given character.
DSA Rust
fn contains_child(&self, ch: char) -> bool {
self.children.[1](&ch)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using get which returns an Option instead of a boolean.
Using insert or remove which modify the map.
✗ Incorrect
The contains_key method checks if a key exists in a HashMap.
3fill in blank
hardFix the error in the DFS function to find the longest word.
DSA Rust
fn dfs(node: &TrieNode, path: &mut String, longest: &mut String) {
if !node.is_word && !path.is_empty() {
return;
}
if path.len() > longest.len() || (path.len() == longest.len() && path < longest) {
*longest = path.clone();
}
for ch in ('a'..='z') {
if let Some(child) = node.children.get(&ch) {
path.push(ch);
dfs(child, path, longest);
path.[1]();
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using clear which empties the whole string.
Using push which adds characters instead of removing.
✗ Incorrect
After exploring a path, pop removes the last character to backtrack.
4fill in blank
hardFill both blanks to build the longest word from the dictionary using Trie.
DSA Rust
fn longest_word(words: Vec<&str>) -> String {
let mut trie = Trie::new();
for word in words {
trie.insert(word);
}
let mut longest = String::new();
let mut path = String::new();
trie.dfs(&trie.root, &mut path, &mut [1]);
[2]
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning path which is empty after DFS.
Returning a new empty string instead of longest.
✗ Incorrect
We pass longest to dfs and return longest after traversal.
5fill in blank
hardFill all three blanks to complete the TrieNode struct and its new method.
DSA Rust
use std::collections::HashMap;
struct TrieNode {
children: HashMap<char, [1]>,
is_word: [2],
}
impl TrieNode {
fn new() -> Self {
TrieNode {
children: HashMap::new(),
is_word: [3],
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using String instead of TrieNode in children map.
Setting is_word to true in new method.
✗ Incorrect
children map chars to TrieNode, is_word is bool, new sets is_word to false.
