Bird
Raised Fist0
DSA Rustprogramming~20 mins

Count Words with Given Prefix in DSA Rust - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Prefix Count Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of prefix count after inserting words
What is the output of the Rust code that inserts words into a prefix count structure and queries the count for prefix "app"?
DSA Rust
struct TrieNode {
    children: std::collections::HashMap<char, TrieNode>,
    count: usize,
}

impl TrieNode {
    fn new() -> Self {
        TrieNode {
            children: std::collections::HashMap::new(),
            count: 0,
        }
    }

    fn insert(&mut self, word: &str) {
        let mut node = self;
        for ch in word.chars() {
            node = node.children.entry(ch).or_insert_with(TrieNode::new);
            node.count += 1;
        }
    }

    fn count_prefix(&self, prefix: &str) -> usize {
        let mut node = self;
        for ch in prefix.chars() {
            if let Some(next) = node.children.get(&ch) {
                node = next;
            } else {
                return 0;
            }
        }
        node.count
    }
}

fn main() {
    let mut root = TrieNode::new();
    root.insert("apple");
    root.insert("app");
    root.insert("application");
    root.insert("apt");
    println!("{}", root.count_prefix("app"));
}
A4
B2
C3
D1
Attempts:
2 left
💡 Hint
Count how many inserted words start with "app".
🧠 Conceptual
intermediate
1:30remaining
Understanding prefix count in a trie
If a trie stores the words ["cat", "car", "cart", "dog"], what is the count of words with prefix "car"?
A3
B2
C1
D0
Attempts:
2 left
💡 Hint
Count words starting exactly with "car" prefix.
🔧 Debug
advanced
2:00remaining
Identify the error in prefix count code
What error does this Rust code produce when counting prefix "ba" after inserting words "bat" and "ball"? Code snippet: let mut root = TrieNode::new(); root.insert("bat"); root.insert("ball"); println!("{}", root.count_prefix("ba")); struct TrieNode { children: std::collections::HashMap, count: usize, } impl TrieNode { fn new() -> Self { TrieNode { children: std::collections::HashMap::new(), count: 0, } } fn insert(&mut self, word: &str) { let mut node = self; for ch in word.chars() { node = node.children.entry(ch).or_insert_with(TrieNode::new); // Missing count increment here } } fn count_prefix(&self, prefix: &str) -> usize { let mut node = self; for ch in prefix.chars() { if let Some(next) = node.children.get(&ch) { node = next; } else { return 0; } } node.count } }
ARuntime panic
B2
CCompilation error
D0
Attempts:
2 left
💡 Hint
Check if counts are updated during insertion.
❓ Predict Output
advanced
2:30remaining
Output after multiple prefix queries
What is the output of the following Rust code printing counts for prefixes "a", "ap", "app", and "b"?
DSA Rust
struct TrieNode {
    children: std::collections::HashMap<char, TrieNode>,
    count: usize,
}

impl TrieNode {
    fn new() -> Self {
        TrieNode {
            children: std::collections::HashMap::new(),
            count: 0,
        }
    }

    fn insert(&mut self, word: &str) {
        let mut node = self;
        for ch in word.chars() {
            node = node.children.entry(ch).or_insert_with(TrieNode::new);
            node.count += 1;
        }
    }

    fn count_prefix(&self, prefix: &str) -> usize {
        let mut node = self;
        for ch in prefix.chars() {
            if let Some(next) = node.children.get(&ch) {
                node = next;
            } else {
                return 0;
            }
        }
        node.count
    }
}

fn main() {
    let mut root = TrieNode::new();
    root.insert("apple");
    root.insert("app");
    root.insert("ape");
    root.insert("bat");
    println!("{} {} {} {}", root.count_prefix("a"), root.count_prefix("ap"), root.count_prefix("app"), root.count_prefix("b"));
}
A4 3 2 1
B3 3 2 1
C4 2 2 1
D3 2 1 1
Attempts:
2 left
💡 Hint
Count words starting with each prefix carefully.
🚀 Application
expert
3:00remaining
Number of words with prefix after deletions
Given a trie that supports insertions and deletions, after inserting words ["test", "team", "teach", "tear"] and deleting "team", what is the count of words with prefix "te"?
DSA Rust
struct TrieNode {
    children: std::collections::HashMap<char, TrieNode>,
    count: usize,
    end_count: usize,
}

impl TrieNode {
    fn new() -> Self {
        TrieNode {
            children: std::collections::HashMap::new(),
            count: 0,
            end_count: 0,
        }
    }

    fn insert(&mut self, word: &str) {
        let mut node = self;
        for ch in word.chars() {
            node = node.children.entry(ch).or_insert_with(TrieNode::new);
            node.count += 1;
        }
        node.end_count += 1;
    }

    fn delete(&mut self, word: &str) -> bool {
        if !self._delete(word, 0) {
            return false;
        }
        true
    }

    fn _delete(&mut self, word: &str, index: usize) -> bool {
        if index == word.len() {
            if self.end_count == 0 {
                return false;
            }
            self.end_count -= 1;
            self.count -= 1;
            return true;
        }
        let ch = word.chars().nth(index).unwrap();
        if let Some(child) = self.children.get_mut(&ch) {
            if child._delete(word, index + 1) {
                self.count -= 1;
                if child.count == 0 {
                    self.children.remove(&ch);
                }
                return true;
            }
        }
        false
    }

    fn count_prefix(&self, prefix: &str) -> usize {
        let mut node = self;
        for ch in prefix.chars() {
            if let Some(next) = node.children.get(&ch) {
                node = next;
            } else {
                return 0;
            }
        }
        node.count
    }
}

fn main() {
    let mut root = TrieNode::new();
    root.insert("test");
    root.insert("team");
    root.insert("teach");
    root.insert("tear");
    root.delete("team");
    println!("{}", root.count_prefix("te"));
}
A3
B4
C2
D1
Attempts:
2 left
💡 Hint
Count words starting with "te" after removing "team".

Practice

(1/5)
1. What does the problem "Count Words with Given Prefix" ask you to do?
easy
A. Find the longest word in a list
B. Count how many words in a list start with a specific prefix
C. Count the total number of characters in all words
D. Sort the words alphabetically

Solution

  1. Step 1: Understand the problem statement

    The problem asks to find how many words start with a given prefix, not about length or sorting.
  2. Step 2: Identify the key task

    Counting words that begin with the prefix is the main task.
  3. Final Answer:

    Count how many words in a list start with a specific prefix -> Option B
  4. Quick Check:

    Count words starting with prefix = Count how many words in a list start with a specific prefix [OK]
Hint: Focus on words starting with prefix, not full word or sorting [OK]
Common Mistakes:
  • Confusing prefix with substring anywhere in word
  • Counting total characters instead of words
  • Sorting words instead of counting
2. Which of the following Rust code snippets correctly checks if a word starts with a given prefix prefix?
easy
A. word.starts_with(prefix)
B. word.contains(prefix)
C. word.ends_with(prefix)
D. word == prefix

Solution

  1. Step 1: Recall Rust string methods

    Rust's starts_with method checks if a string begins with a given substring.
  2. Step 2: Compare options

    contains checks anywhere, ends_with checks suffix, and == checks full equality, so only starts_with fits.
  3. Final Answer:

    word.starts_with(prefix) -> Option A
  4. Quick Check:

    Use starts_with() to check prefix [OK]
Hint: Use starts_with() method to check prefix in Rust strings [OK]
Common Mistakes:
  • Using contains() which matches anywhere, not just prefix
  • Using ends_with() which checks suffix
  • Comparing full equality instead of prefix
3. What is the output of this Rust code?
let words = vec!["apple", "app", "application", "banana"];
let prefix = "app";
let count = words.iter().filter(|w| w.starts_with(prefix)).count();
println!("{}", count);
medium
A. 3
B. 2
C. 1
D. 4

Solution

  1. Step 1: Identify words starting with "app"

    Words are "apple", "app", "application", and "banana". The first three start with "app".
  2. Step 2: Count matching words

    Count is 3 because "apple", "app", and "application" start with "app".
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    3 words start with "app" [OK]
Hint: Count words where starts_with(prefix) is true [OK]
Common Mistakes:
  • Counting only exact matches
  • Including words that don't start with prefix
  • Off-by-one counting errors
4. The following Rust code tries to count words starting with a prefix but gives wrong output. What is the bug?
let words = vec!["cat", "car", "dog", "scare"];
let prefix = "car";
let count = words.iter().filter(|w| w.contains(prefix)).count();
println!("{}", count);
medium
A. Missing semicolon after count declaration
B. Prefix variable is not declared correctly
C. The vector words is empty
D. Using contains() instead of starts_with() causes wrong matches

Solution

  1. Step 1: Understand difference between contains() and starts_with()

    contains() checks if prefix appears anywhere, not just at start.
  2. Step 2: Identify incorrect matches

    "scare" contains "car" but does not start with "car", so contains() wrongly counts it.
  3. Final Answer:

    Using contains() instead of starts_with() causes wrong matches -> Option D
  4. Quick Check:

    Use starts_with() to count prefix matches [OK]
Hint: Replace contains() with starts_with() to fix prefix counting [OK]
Common Mistakes:
  • Confusing contains() with starts_with()
  • Assuming contains() only matches prefix
  • Ignoring method differences
5. Given a list of words ["test", "tester", "testing", "toast", "team"] and prefix "te", which Rust code correctly counts words starting with the prefix and ignores case sensitivity?
hard
A. words.iter().filter(|w| w.contains(prefix)).count()
B. words.iter().filter(|w| w.starts_with(prefix)).count()
C. words.iter().filter(|w| w.to_lowercase().starts_with(&prefix.to_lowercase())).count()
D. words.iter().filter(|w| w.ends_with(prefix)).count()

Solution

  1. Step 1: Understand case sensitivity in Rust strings

    Rust's starts_with is case sensitive, so we convert both word and prefix to lowercase.
  2. Step 2: Check each option for case-insensitive prefix check

    words.iter().filter(|w| w.to_lowercase().starts_with(&prefix.to_lowercase())).count() converts both to lowercase before checking prefix, ensuring case-insensitive match. Others do not handle case.
  3. Final Answer:

    words.iter().filter(|w| w.to_lowercase().starts_with(&prefix.to_lowercase())).count() -> Option C
  4. Quick Check:

    Convert both strings to lowercase before starts_with() [OK]
Hint: Lowercase both word and prefix before starts_with() for case-insensitive [OK]
Common Mistakes:
  • Ignoring case sensitivity in starts_with()
  • Using contains() which is wrong for prefix
  • Using ends_with() instead of starts_with()
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