Bird
Raised Fist0
DSA Rustprogramming

Count Words with Given Prefix in DSA Rust

Choose your learning style10 modes available
Mental Model
We want to find how many words start with a certain beginning part (prefix). We look through all words and count those that begin the same way.
Analogy: Imagine a library where you want to count all books whose titles start with the same first few letters, like all books starting with 'The'. You scan the titles and count matches.
words: ["apple", "app", "ape", "bat", "ball"]
prefix: "ap"

Count how many words start with "ap".
Dry Run Walkthrough
Input: words: ["apple", "app", "ape", "bat", "ball"], prefix: "ap"
Goal: Count how many words start with the prefix "ap"
Step 1: Check word "apple" if it starts with "ap"
"apple" starts with "ap" -> count = 1
Why: We found one word starting with the prefix
Step 2: Check word "app" if it starts with "ap"
"app" starts with "ap" -> count = 2
Why: Another word matches the prefix
Step 3: Check word "ape" if it starts with "ap"
"ape" starts with "ap" -> count = 3
Why: Third word matches the prefix
Step 4: Check word "bat" if it starts with "ap"
"bat" does not start with "ap" -> count = 3
Why: No match, count stays the same
Step 5: Check word "ball" if it starts with "ap"
"ball" does not start with "ap" -> count = 3
Why: No match, count stays the same
Result:
Final count = 3
Annotated Code
DSA Rust
fn count_words_with_prefix(words: &[&str], prefix: &str) -> usize {
    let mut count = 0;
    for word in words {
        if word.starts_with(prefix) {
            count += 1;
        }
    }
    count
}

fn main() {
    let words = ["apple", "app", "ape", "bat", "ball"];
    let prefix = "ap";
    let result = count_words_with_prefix(&words, prefix);
    println!("{}", result);
}
for word in words {
iterate over each word in the list
if word.starts_with(prefix) {
check if current word begins with the prefix
count += 1;
increment count for each matching word
OutputSuccess
3
Complexity Analysis
Time: O(n * m) because we check each of the n words and compare up to m characters of the prefix
Space: O(1) because we only use a counter variable regardless of input size
vs Alternative: Compared to building a trie for prefix counting, this direct check is simpler but slower for many queries
Edge Cases
empty words list
returns 0 because no words to check
DSA Rust
for word in words {
empty prefix
counts all words because every word starts with empty string
DSA Rust
if word.starts_with(prefix) {
no words match prefix
returns 0 because no word starts with given prefix
DSA Rust
if word.starts_with(prefix) {
When to Use This Pattern
When you need to count how many strings start with a certain prefix, use a simple loop with starts_with check for a straightforward solution.
Common Mistakes
Mistake: Checking if prefix starts with word instead of word starts with prefix
Fix: Use word.starts_with(prefix) to correctly check prefix at start of word
Summary
Counts how many words in a list begin with a given prefix.
Use when you want to find how many words share the same starting letters.
The key is to check each word's start against the prefix and count matches.

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