Count Words with Given Prefix in DSA C# - Time & Space Complexity
We want to understand how the time to count words with a certain prefix grows as the number of words or prefix length changes.
How does the work increase when we have more words or longer prefixes?
Analyze the time complexity of the following code snippet.
public int CountWordsWithPrefix(string[] words, string prefix) {
int count = 0;
foreach (var word in words) {
if (word.StartsWith(prefix)) {
count++;
}
}
return count;
}
This code counts how many words in the list start with the given prefix.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each word to see if it starts with the prefix.
- How many times: Once for every word in the list (n times), and for each check, it compares characters up to the prefix length (m times).
As the number of words (n) grows, the code checks more words. Also, longer prefixes (m) mean more character comparisons per word.
| Input Size (n words, prefix length m) | Approx. Operations |
|---|---|
| 10 words, prefix length 3 | About 10 * 3 = 30 checks |
| 100 words, prefix length 3 | About 100 * 3 = 300 checks |
| 1000 words, prefix length 5 | About 1000 * 5 = 5000 checks |
Pattern observation: The work grows linearly with the number of words and also linearly with the prefix length.
Time Complexity: O(n * m)
This means the time grows proportionally to the number of words times the length of the prefix.
[X] Wrong: "Checking the prefix is always O(1) because it's just one operation."
[OK] Correct: Actually, checking the prefix compares each character up to the prefix length, so it takes O(m) time, not constant time.
Understanding how prefix checks scale helps you explain and improve search operations, a common task in coding interviews and real applications.
"What if we used a Trie data structure instead of checking each word? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem statement
The problem asks to count words that begin with a given prefix, not to sort or replace words.Step 2: Identify the key action
Counting words starting with the prefix is the main task.Final Answer:
Count how many words in a list start with a specific prefix -> Option AQuick Check:
Count words with prefix = Count how many words in a list start with a specific prefix [OK]
- Confusing counting with sorting
- Thinking the task is to replace prefixes
- Ignoring the prefix condition
word starts with a prefix prefix?Solution
Step 1: Recall string methods in C#
The methodStartsWithchecks if a string begins with a given substring.Step 2: Compare options
Containschecks anywhere in the string,EndsWithchecks the end, and==checks exact equality.Final Answer:
if (word.StartsWith(prefix)) { /* do something */ } -> Option DQuick Check:
Use StartsWith to check prefix [OK]
- Using Contains instead of StartsWith
- Checking equality instead of prefix
- Using EndsWith which checks suffix
string[] words = {"apple", "app", "application", "banana"};
string prefix = "app";
int count = 0;
foreach (var word in words) {
if (word.StartsWith(prefix)) {
count++;
}
}
Console.WriteLine(count);Solution
Step 1: Check each word against prefix "app"
Words: "apple" (yes), "app" (yes), "application" (yes), "banana" (no).Step 2: Count matches
Three words start with "app", so count = 3.Final Answer:
3 -> Option CQuick Check:
Words starting with "app" = 3 [OK]
- Counting only exact matches
- Including words that contain prefix but don't start with it
- Off-by-one counting errors
string[] words = {"cat", "car", "dog", "cart"};
string prefix = "car";
int count = 0;
for (int i = 0; i <= words.Length; i++) {
if (words[i].StartsWith(prefix)) {
count++;
}
}
Console.WriteLine(count);Solution
Step 1: Analyze the for loop condition
The loop runs from i = 0 to i <= words.Length, which causes an index out of range error because valid indices are 0 to words.Length - 1.Step 2: Correct the loop condition
Change condition to i < words.Length to avoid accessing invalid index.Final Answer:
The loop condition should be i < words.Length instead of <=. -> Option AQuick Check:
Loop index must be less than array length [OK]
- Using <= instead of < in loop condition
- Reinitializing count inside loop
- Misusing StartsWith method
["tree", "trie", "trigger", "trip", "try", "matrix"] and prefix "tri", which C# code snippet correctly counts the words starting with the prefix and prints the count?Solution
Step 1: Understand the requirement
We need to count words starting exactly with prefix "tri".Step 2: Evaluate each option
int count = words.Count(word => word.StartsWith(prefix)); Console.WriteLine(count); uses LINQ Count with StartsWith correctly.
int count = 0; foreach(var word in words) { if(word.Contains(prefix)) count++; } Console.WriteLine(count); uses Contains which counts words containing prefix anywhere.
int count = 0; for(int i=0; i<=words.Length; i++) { if(words[i].StartsWith(prefix)) count++; } Console.WriteLine(count); has loop with <= causing index error.
int count = words.Length; Console.WriteLine(count); counts all words ignoring prefix.Final Answer:
int count = words.Count(word => word.StartsWith(prefix)); Console.WriteLine(count); -> Option BQuick Check:
Use LINQ Count with StartsWith for prefix count [OK]
- Using Contains instead of StartsWith
- Loop index out of range errors
- Counting all words without prefix check
Ready to prove it?
Pass the test and this pattern moves unknown
