Count Words with Given Prefix in DSA Javascript - Time & Space Complexity
We want to understand how the time needed to count words with a certain prefix grows as the list of words gets bigger.
How does the number of steps change when we have more words or longer prefixes?
Analyze the time complexity of the following code snippet.
function countWordsWithPrefix(words, prefix) {
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.
- 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).
- Inside each check: Comparing characters of the prefix with the start of the word (up to prefix length m).
As the number of words (n) grows, the code checks each word once. For each word, it compares up to m characters where m is the prefix length.
| Input Size (n) | Approx. Operations (checks x prefix length) |
|---|---|
| 10 | 10 x m |
| 100 | 100 x m |
| 1000 | 1000 x m |
Pattern observation: The total work grows linearly with the number of words and also depends on the prefix length.
Time Complexity: O(n x m)
This means the time grows proportionally to the number of words and the length of the prefix we check.
[X] Wrong: "Checking the prefix is just O(1) because prefix length is small and fixed."
[OK] Correct: Even if prefix is short, it still takes time proportional to its length for each word, so prefix length matters in total time.
Understanding how loops and string checks add up helps you explain your code clearly and shows you can think about efficiency in real problems.
"What if the words were stored in a trie data structure? How would the time complexity change when counting words with the prefix?"
Practice
countWordsWithPrefix(words, prefix) do when given a list of words and a prefix?Solution
Step 1: Understand the function purpose
The function checks each word to see if it starts with the given prefix.Step 2: Count matching words
It counts only those words that begin exactly with the prefix, ignoring others.Final Answer:
Counts how many words start with the given prefix -> Option DQuick Check:
Starts with prefix = Count [OK]
- Counting words containing prefix anywhere
- Counting words ending with prefix
- Counting total words instead of filtered ones
word starts with a prefix prefix in JavaScript?Solution
Step 1: Recall JavaScript string methods
JavaScript strings have a method calledstartsWith()to check prefix.Step 2: Match method name
OnlystartsWith()is the correct method; others do not exist.Final Answer:
word.startsWith(prefix) -> Option CQuick Check:
Correct method name = startsWith [OK]
- Using non-existent methods like hasPrefix
- Using incorrect method names like beginWith
- Confusing startsWith with other string methods
const words = ['apple', 'app', 'application', 'banana'];
const prefix = 'app';
function countWordsWithPrefix(words, prefix) {
let count = 0;
for (const word of words) {
if (word.startsWith(prefix)) {
count++;
}
}
return count;
}
console.log(countWordsWithPrefix(words, prefix));Solution
Step 1: Check each word against prefix 'app'
'apple', 'app', and 'application' all start with 'app'. 'banana' does not.Step 2: Count matching words
There are 3 words starting with 'app', so count is 3.Final Answer:
3 -> Option AQuick Check:
Words starting with 'app' = 3 [OK]
- Counting words containing prefix anywhere
- Missing one of the matching words
- Counting all words regardless of prefix
function countWordsWithPrefix(words, prefix) {
let count = 0;
for (let i = 0; i <= words.length; i++) {
if (words[i].startsWith(prefix)) {
count++;
}
}
return count;
}Solution
Step 1: Analyze loop condition
The loop runs with i from 0 to words.length inclusive, but array indices go from 0 to words.length - 1.Step 2: Identify out of bounds access
At i = words.length, words[i] is undefined, so calling startsWith causes an error.Final Answer:
Loop goes out of bounds causing an error -> Option BQuick Check:
Loop index must be less than length [OK]
- Using <= instead of < in loop condition
- Not checking array bounds before access
- Assuming startsWith works on undefined
words = ['Test', 'testing', 'Tester', 'tent', 'team'] and prefix 'te', which code snippet correctly counts words starting with the prefix ignoring case sensitivity?Solution
Step 1: Understand case sensitivity issue
Direct startsWith is case sensitive, so 'Test' and 'test' differ.Step 2: Use toLowerCase() to normalize
Convert both word and prefix to lowercase before checking startsWith to ignore case.Final Answer:
words.filter(w => w.toLowerCase().startsWith(prefix.toLowerCase())).length -> Option AQuick Check:
Normalize case before prefix check [OK]
- Ignoring case sensitivity
- Using includes instead of startsWith
- Using endsWith instead of startsWith
Ready to prove it?
Pass the test and this pattern moves unknown
