Count Words with Given Prefix in DSA Typescript - Time & Space Complexity
We want to understand how the time needed to count words with a given prefix changes as the number of words grows.
Specifically, how does the search for words starting with a prefix affect performance?
Analyze the time complexity of the following code snippet.
function countWordsWithPrefix(words: string[], prefix: string): number {
let count = 0;
for (const word of words) {
if (word.startsWith(prefix)) {
count++;
}
}
return count;
}
This code counts how many words in the list start with the given prefix by checking each word one by one.
- Primary operation: Looping through each word and checking if it starts with the prefix.
- How many times: Once for every word in the list (n times).
As the number of words increases, the time to check all words grows roughly in direct proportion.
| 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 done.
Time Complexity: O(n * m)
This means the time grows with the number of words (n) and the length of the prefix (m) because each word is checked against the prefix.
[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, so it depends on both n and m.
Understanding how prefix checks scale helps you explain trade-offs in searching and string matching, a common topic in interviews.
"What if we used a trie (prefix tree) instead of checking each word? How would the time complexity change?"
Practice
countWordsStartingWith(words: string[], prefix: string): number do in the context of counting words with a given prefix?Solution
Step 1: Understand the function purpose
The function is designed to count words that begin with a specific prefix, not just contain it anywhere.Step 2: Compare options with function goal
Only Counts how many words in the list start with the given prefix matches the goal of counting words starting exactly with the prefix.Final Answer:
Counts how many words in the list start with the given prefix -> Option CQuick Check:
Counting words starting with prefix = Counts how many words in the list start with the given prefix [OK]
- Confusing 'start with' and 'contain' prefix
- Thinking it returns words instead of count
- Assuming it counts characters, not words
pre in an array words?Solution
Step 1: Identify correct method to filter words
Thefiltermethod returns an array of words starting with the prefix, thenlengthcounts them.Step 2: Check other options for correctness
words.map(word => word.startsWith(pre)).length returns an array of booleans, so length is total words, not count of matches. words.reduce((count, word) => count + word.includes(pre), 0) usesincludesincorrectly and sums booleans without conversion. words.forEach(word => word.startsWith(pre)) does not return a count.Final Answer:
words.filter(word => word.startsWith(pre)).length -> Option AQuick Check:
Filter + length counts matches = words.filter(word => word.startsWith(pre)).length [OK]
- Using map instead of filter for counting
- Using includes instead of startsWith
- Using forEach without counting
const words = ['apple', 'app', 'application', 'banana', 'apply']; const prefix = 'app'; const count = words.filter(word => word.startsWith(prefix)).length; console.log(count);
Solution
Step 1: Identify words starting with 'app'
Words starting with 'app' are 'apple', 'app', 'application', and 'apply' (4 words).Step 2: Count these words
Counting them gives 4.Final Answer:
4 -> Option BQuick Check:
Words starting with 'app' = 4 [OK]
- Counting 'banana' mistakenly
- Counting only exact 'app' word
- Confusing includes with startsWith
pre, but it returns 0. What is the error?const words = ['prefix', 'preach', 'prevent', 'post'];
const pre = 'pre';
let count = 0;
for (let i = 0; i < words.length; i++) {
if (words[i].startWith(pre)) {
count++;
}
}
console.log(count);Solution
Step 1: Check method name correctness
The method to check prefix isstartsWith, but code usesstartWith, which is undefined.Step 2: Understand effect of typo
Because of the typo, condition is always false, so count remains 0.Final Answer:
Method name should be startsWith, not startWith -> Option AQuick Check:
Correct method name fixes count [OK]
- Using startWith instead of startsWith
- Incorrect loop index start
- Wrong count initialization
Solution
Step 1: Understand prefix query optimization
Trie stores words by characters in a tree, allowing fast prefix searches.Step 2: Compare other data structures
Sorted arrays require binary search but less efficient for many prefix queries. Hash maps store full words, not prefixes. Stacks do not support prefix queries efficiently.Final Answer:
Trie (Prefix Tree) -> Option DQuick Check:
Trie enables fast prefix counts [OK]
- Choosing array or hash map for prefix queries
- Not knowing Trie supports prefix efficiently
- Confusing stack usage for prefix search
Ready to prove it?
Pass the test and this pattern moves unknown
