Bird
Raised Fist0
DSA Rustprogramming~10 mins

Prefix Search Using Trie in DSA Rust - Interactive Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a new Trie node with empty children.

DSA Rust
struct TrieNode {
    children: [Option<Box<TrieNode>>; 26],
    is_end_of_word: bool,
}

impl TrieNode {
    fn new() -> Self {
        TrieNode {
            children: [1],
            is_end_of_word: false,
        }
    }
}
Drag options to blanks, or click blank then click option'
A[Some; 26]
B[None; 26]
C[Box::new(TrieNode); 26]
D[0; 26]
Attempts:
3 left
💡 Hint
Common Mistakes
Using Some without a value causes errors.
Trying to initialize with zeros instead of None.
Using Box::new without creating actual nodes.
2fill in blank
medium

Complete the code to insert a character into the Trie children array.

DSA Rust
fn insert_char(&mut self, ch: char) {
    let index = (ch as usize) - ('a' as usize);
    if self.children[index].is_none() {
        self.children[index] = Some(Box::new([1]));
    }
}
Drag options to blanks, or click blank then click option'
ATrieNode::new()
BTrieNode
CBox::new(TrieNode)
DNone
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning None instead of a new node.
Using the type name without calling new().
Trying to box the type instead of the instance.
3fill in blank
hard

Fix the error in the search function to correctly check if a prefix exists in the Trie.

DSA Rust
fn search_prefix(&self, prefix: &str) -> bool {
    let mut node = self;
    for ch in prefix.chars() {
        let index = (ch as usize) - ('a' as usize);
        match &node.children[index] {
            Some(next_node) => node = [1],
            None => return false,
        }
    }
    true
}
Drag options to blanks, or click blank then click option'
A*next_node
B&next_node
Cnext_node
Dnode.children[index].as_ref()
Attempts:
3 left
💡 Hint
Common Mistakes
Dereferencing the Box causing type mismatch.
Using &next_node which is a reference to a reference.
Trying to access children again instead of moving forward.
4fill in blank
hard

Fill both blanks to complete the insert function that marks the end of a word in the Trie.

DSA Rust
fn insert(&mut self, word: &str) {
    let mut node = self;
    for ch in word.chars() {
        let index = (ch as usize) - ('a' as usize);
        if node.children[index].is_none() {
            node.children[index] = Some(Box::new([1]));
        }
        node = node.children[index].as_mut().unwrap();
    }
    node.[2] = true;
}
Drag options to blanks, or click blank then click option'
ATrieNode::new()
Bis_end_of_word
Cis_word_end
Dend_of_word
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong field names for the end marker.
Not creating new nodes properly.
Forgetting to unwrap the Option before assignment.
5fill in blank
hard

Fill all three blanks to complete a function that returns all words in the Trie starting with a given prefix.

DSA Rust
fn collect_words(node: &TrieNode, prefix: String, results: &mut Vec<String>) {
    if node.[1] {
        results.push(prefix.clone());
    }
    for i in 0..26 {
        if let Some(child) = &node.children[i] {
            let ch = (i as u8 + b'a') as char;
            collect_words(child, prefix.clone() + &[2], results);
        }
    }
}

fn words_with_prefix(root: &TrieNode, prefix: &str) -> Vec<String> {
    let mut node = root;
    for ch in prefix.chars() {
        let index = (ch as usize) - ('a' as usize);
        match &node.children[index] {
            Some(next_node) => node = next_node,
            None => return vec![],
        }
    }
    let mut results = Vec::new();
    collect_words(node, prefix.to_string(), &mut [3]);
    results
}
Drag options to blanks, or click blank then click option'
Ais_end_of_word
Bch.to_string()
Cresults
Dprefix
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong field names for word end check.
Concatenating char without converting to string.
Passing wrong variable for results vector.

Practice

(1/5)
1. What is the main purpose of using a Trie data structure in prefix search?
easy
A. To efficiently find all words that start with a given prefix
B. To sort words alphabetically
C. To store numbers in sorted order
D. To perform arithmetic operations quickly

Solution

  1. Step 1: Understand Trie usage

    A Trie stores strings in a tree-like structure where each node represents a character, making prefix searches efficient.
  2. Step 2: Identify prefix search goal

    Prefix search requires finding all words starting with a given prefix, which Trie supports directly by traversing nodes.
  3. Final Answer:

    To efficiently find all words that start with a given prefix -> Option A
  4. Quick Check:

    Trie = prefix search efficiency [OK]
Hint: Trie nodes represent characters for fast prefix lookup [OK]
Common Mistakes:
  • Confusing Trie with sorting data structure
  • Thinking Trie is for numeric operations
  • Assuming Trie stores full words only at root
2. Which of the following Rust code snippets correctly defines a Trie node struct for prefix search?
easy
A. struct TrieNode { children: HashMap, is_end: bool }
B. struct TrieNode { children: Vec<char>, is_end: bool }
C. struct TrieNode { children: String, is_end: bool }
D. struct TrieNode { children: i32, is_end: bool }

Solution

  1. Step 1: Check children type for TrieNode

    Children must map characters to child nodes, so HashMap is correct for recursive structure without size issues.
  2. Step 2: Validate other options

    Vec<char> or String cannot map characters to nodes; i32 is invalid for children.
  3. Final Answer:

    struct TrieNode { children: HashMap, is_end: bool } -> Option A
  4. Quick Check:

    Children map chars to nodes = struct TrieNode { children: HashMap, is_end: bool } [OK]
Hint: Use HashMap for children in Rust Trie [OK]
Common Mistakes:
  • Using Vec<char> instead of mapping to nodes
  • Using String for children instead of node references
  • Using primitive types like i32 for children
3. Given the following Rust code snippet for inserting words into a Trie and searching for prefix "ca":
let mut trie = Trie::new();
trie.insert("cat");
trie.insert("car");
trie.insert("dog");
let result = trie.starts_with("ca");
println!("{:?}", result);
What will be printed?
medium
A. ["cat", "car", "dog"]
B. ["cat", "car"]
C. ["dog"]
D. []

Solution

  1. Step 1: Insert words into Trie

    Words "cat", "car", and "dog" are inserted. "cat" and "car" share prefix "ca".
  2. Step 2: Search for prefix "ca"

    Searching prefix "ca" returns all words starting with "ca", which are "cat" and "car".
  3. Final Answer:

    ["cat", "car"] -> Option B
  4. Quick Check:

    Prefix "ca" matches cat, car [OK]
Hint: Prefix search returns words starting exactly with given prefix [OK]
Common Mistakes:
  • Including words without the prefix
  • Returning empty list if prefix exists
  • Confusing prefix search with full word search
4. Consider this Rust code snippet for prefix search in a Trie:
fn starts_with(&self, prefix: &str) -> bool {
    let mut node = &self.root;
    for ch in prefix.chars() {
        if !node.children.contains_key(&ch) {
            return false;
        }
        node = node.children.get(&ch).unwrap();
    }
    true
}
What is the main issue with this code snippet?
medium
A. Cannot assign &TrieNode to node because of lifetime mismatch
B. Missing mutable keyword for node variable
C. Using unwrap() without checking Option
D. Incorrect return type for starts_with function

Solution

  1. Step 1: Analyze function purpose

    This implements prefix existence check (returns bool).
  2. Step 2: Identify mismatch for prefix search

    Prefix search requires returning all words with the prefix (e.g. Vec<String>), not just bool.
  3. Final Answer:

    Incorrect return type for starts_with function -> Option D
  4. Quick Check:

    Prefix search needs Vec<String> not bool [OK]
Hint: Verify return type matches prefix search requirements [OK]
Common Mistakes:
  • Confusing prefix existence (bool) with full prefix search (list)
  • Assuming unwrap() causes runtime error here
  • Forgetting Rust borrow checker rules
5. You want to extend a Trie in Rust to support prefix search that returns all words starting with a prefix, but also limit results to a maximum of 2 words. Which approach is best?
hard
A. Use a HashSet to store all words and filter after search
B. Store only 2 words per node during insertion
C. Modify DFS traversal to stop collecting words after 2 matches
D. Return only the first word found with the prefix

Solution

  1. Step 1: Understand prefix search with limit

    We want to find all words starting with prefix but stop after 2 matches to save time.
  2. Step 2: Modify DFS traversal

    During DFS from prefix node, keep count of collected words and stop recursion once 2 words are found.
  3. Step 3: Evaluate other options

    Storing only 2 words per node loses data; filtering after search is inefficient; returning one word is incomplete.
  4. Final Answer:

    Modify DFS traversal to stop collecting words after 2 matches -> Option C
  5. Quick Check:

    Limit results by stopping DFS early [OK]
Hint: Stop DFS early to limit prefix search results [OK]
Common Mistakes:
  • Limiting stored words per node loses data
  • Filtering after full search wastes time
  • Returning only one word ignores requirement
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard