Count Words with Given Prefix in DSA Java - Time & Space Complexity
We want to understand how long it takes to count words that start with a certain prefix.
How does the time needed change as the number of words or prefix length grows?
Analyze the time complexity of the following code snippet.
public int countWordsWithPrefix(String[] words, String prefix) {
int count = 0;
for (String word : words) {
if (word.startsWith(prefix)) {
count++;
}
}
return count;
}
This code counts how many words in the array 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).
As the number of words grows, the time to check all words grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 prefix checks |
| 100 | About 100 prefix checks |
| 1000 | About 1000 prefix checks |
Pattern observation: Doubling the number of words roughly doubles the work.
Time Complexity: O(n * m)
This means the time grows with the number of words (n) and the length of the prefix (m).
[X] Wrong: "Checking prefix is always O(1) so total time is just O(n)."
[OK] Correct: Checking if a word starts with a prefix takes time proportional to the prefix length (m), so it is not constant time.
Understanding this helps you explain how simple loops and string checks affect performance in real tasks.
"What if the words were stored in a trie data structure? How would the time complexity change?"
Practice
Solution
Step 1: Understand the prefix concept
The prefix is the starting part of a word. We need to check if words start with this prefix.Step 2: Count matching words
We count all words that begin with the given prefix from the list.Final Answer:
Count how many words in a list start with a specific prefix -> Option AQuick Check:
Prefix means start of word = Count matching words [OK]
- Counting words containing prefix anywhere, not just start
- Confusing prefix with suffix
- Counting characters instead of words
word starts with a prefix pref?Solution
Step 1: Recall Java String methods
Java'sstartsWithmethod checks if a string begins with a given prefix.Step 2: Match method to requirement
Since we want to check the start,word.startsWith(pref)is correct.Final Answer:
word.startsWith(pref) -> Option DQuick Check:
startsWith checks prefix = word.startsWith(pref) [OK]
- Using contains() which checks anywhere in string
- Using equals() which checks full string equality
- Using endsWith() which checks suffix
String[] words = {"apple", "app", "application", "banana"};
String prefix = "app";
int count = 0;
for (String w : words) {
if (w.startsWith(prefix)) {
count++;
}
}
System.out.println(count);Solution
Step 1: Check each word against prefix "app"
Words starting with "app" are "apple", "app", and "application" (3 words).Step 2: Count matching words
Count increments 3 times for these words.Final Answer:
3 -> Option AQuick Check:
3 words start with "app" = 3 [OK]
- Counting only exact matches
- Counting words containing prefix anywhere
- Off-by-one errors in counting
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++;
}
}
System.out.println(count);Solution
Step 1: Analyze loop condition
The loop runs from i = 0 to i <= words.length, which causes an IndexOutOfBoundsException because last index is words.length - 1.Step 2: Correct loop condition
Change condition to i < words.length to avoid accessing invalid index.Final Answer:
Loop condition should be i < words.length, not i <= words.length -> Option CQuick Check:
Array index max is length-1 = fix loop condition [OK]
- Using <= instead of < in loop condition
- Ignoring array index limits
- Misusing startsWith method
["tree", "trie", "trigger", "trip", "trick"] and prefix "tri", which Java code snippet correctly counts the words starting with the prefix using streams?Solution
Step 1: Use stream filter with startsWith
The filter should keep words starting with the prefix usingw.startsWith(prefix).Step 2: Count filtered words
Usecount()to get the number of matching words. The result is a long type.Final Answer:
long count = Arrays.stream(words).filter(w -> w.startsWith(prefix)).count(); -> Option BQuick Check:
Filter with startsWith + count() = long count = Arrays.stream(words).filter(w -> w.startsWith(prefix)).count(); [OK]
- Using map instead of filter
- Using contains instead of startsWith
- Using endsWith instead of startsWith
Ready to prove it?
Pass the test and this pattern moves unknown
