Bird
Raised Fist0
DSA Javascriptprogramming

Count Words with Given Prefix in DSA Javascript

Choose your learning style10 modes available
Mental Model
We want to find how many words start with a certain beginning part (prefix). We check each word to see if it begins with that prefix.
Analogy: Imagine you have a box of books and you want to count how many titles start with the word 'The'. You look at each title and count only those that start with 'The'.
Words: [apple, app, application, banana, bat]
Prefix: app
Check each word if it starts with 'app'
Dry Run Walkthrough
Input: words: ['apple', 'app', 'application', 'banana', 'bat'], prefix: 'app'
Goal: Count how many words start with 'app'
Step 1: Check if 'apple' starts with 'app'
apple (starts with 'app') -> count = 1
Why: We found one word starting with the prefix
Step 2: Check if 'app' starts with 'app'
apple -> app (starts with 'app') -> count = 2
Why: Another word matches the prefix
Step 3: Check if 'application' starts with 'app'
apple -> app -> application (starts with 'app') -> count = 3
Why: Another word matches the prefix
Step 4: Check if 'banana' starts with 'app'
apple -> app -> application -> banana (does not start with 'app') -> count = 3
Why: No match, count stays the same
Step 5: Check if 'bat' starts with 'app'
apple -> app -> application -> banana -> bat (does not start with 'app') -> count = 3
Why: No match, count stays the same
Result:
Final count = 3
Annotated Code
DSA Javascript
class PrefixCounter {
  constructor(words) {
    this.words = words;
  }

  countWordsWithPrefix(prefix) {
    let count = 0;
    for (const word of this.words) {
      if (word.startsWith(prefix)) {
        count++;
      }
    }
    return count;
  }
}

// Driver code
const words = ['apple', 'app', 'application', 'banana', 'bat'];
const prefix = 'app';
const counter = new PrefixCounter(words);
console.log(counter.countWordsWithPrefix(prefix));
for (const word of this.words) {
iterate over each word to check prefix
if (word.startsWith(prefix)) {
check if current word starts with the prefix
count++;
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(n) for storing the list of words
vs Alternative: Compared to building a trie for prefix counting, this approach is simpler but slower for many queries; trie offers faster prefix queries after setup
Edge Cases
empty words list
returns 0 because no words to check
DSA Javascript
for (const word of this.words) {
empty prefix string
counts all words because every word starts with empty string
DSA Javascript
if (word.startsWith(prefix)) {
no words match prefix
returns 0 because no word starts with given prefix
DSA Javascript
if (word.startsWith(prefix)) {
When to Use This Pattern
When you need to count how many strings start with a certain prefix, use this pattern of checking each word's start to find matches.
Common Mistakes
Mistake: Checking if prefix starts with word instead of word starts with prefix
Fix: Use word.startsWith(prefix) to correctly check the word's beginning
Mistake: Not handling empty prefix which should count all words
Fix: Allow empty prefix and count all words since all start with empty string
Summary
Counts how many words in a list start with a given prefix.
Use when you want to find how many words share the same beginning letters.
The key is to check each word's start against the prefix and count matches.

Practice

(1/5)
1. What does the function countWordsWithPrefix(words, prefix) do when given a list of words and a prefix?
easy
A. Counts how many words contain the prefix anywhere
B. Counts the total number of words in the list
C. Counts how many words end with the given prefix
D. Counts how many words start with the given prefix

Solution

  1. Step 1: Understand the function purpose

    The function checks each word to see if it starts with the given prefix.
  2. Step 2: Count matching words

    It counts only those words that begin exactly with the prefix, ignoring others.
  3. Final Answer:

    Counts how many words start with the given prefix -> Option D
  4. Quick Check:

    Starts with prefix = Count [OK]
Hint: Look for words starting exactly with prefix [OK]
Common Mistakes:
  • Counting words containing prefix anywhere
  • Counting words ending with prefix
  • Counting total words instead of filtered ones
2. Which of the following is the correct syntax to check if a string word starts with a prefix prefix in JavaScript?
easy
A. word.beginWith(prefix)
B. word.hasPrefix(prefix)
C. word.startsWith(prefix)
D. word.starts(prefix)

Solution

  1. Step 1: Recall JavaScript string methods

    JavaScript strings have a method called startsWith() to check prefix.
  2. Step 2: Match method name

    Only startsWith() is the correct method; others do not exist.
  3. Final Answer:

    word.startsWith(prefix) -> Option C
  4. Quick Check:

    Correct method name = startsWith [OK]
Hint: Use startsWith() method for prefix check [OK]
Common Mistakes:
  • Using non-existent methods like hasPrefix
  • Using incorrect method names like beginWith
  • Confusing startsWith with other string methods
3. What is the output of the following code?
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));
medium
A. 3
B. 2
C. 1
D. 4

Solution

  1. Step 1: Check each word against prefix 'app'

    'apple', 'app', and 'application' all start with 'app'. 'banana' does not.
  2. Step 2: Count matching words

    There are 3 words starting with 'app', so count is 3.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    Words starting with 'app' = 3 [OK]
Hint: Count words starting exactly with prefix [OK]
Common Mistakes:
  • Counting words containing prefix anywhere
  • Missing one of the matching words
  • Counting all words regardless of prefix
4. The following code is intended to count words starting with a prefix, but it has a bug. What is the bug?
function countWordsWithPrefix(words, prefix) {
  let count = 0;
  for (let i = 0; i <= words.length; i++) {
    if (words[i].startsWith(prefix)) {
      count++;
    }
  }
  return count;
}
medium
A. startsWith method is used incorrectly
B. Loop goes out of bounds causing an error
C. count variable is not initialized
D. Prefix is not passed as a parameter

Solution

  1. 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.
  2. Step 2: Identify out of bounds access

    At i = words.length, words[i] is undefined, so calling startsWith causes an error.
  3. Final Answer:

    Loop goes out of bounds causing an error -> Option B
  4. Quick Check:

    Loop index must be less than length [OK]
Hint: Use i < words.length, not <= [OK]
Common Mistakes:
  • Using <= instead of < in loop condition
  • Not checking array bounds before access
  • Assuming startsWith works on undefined
5. Given the array words = ['Test', 'testing', 'Tester', 'tent', 'team'] and prefix 'te', which code snippet correctly counts words starting with the prefix ignoring case sensitivity?
hard
A. words.filter(w => w.toLowerCase().startsWith(prefix.toLowerCase())).length
B. words.filter(w => w.startsWith(prefix)).length
C. words.filter(w => w.includes(prefix)).length
D. words.filter(w => w.endsWith(prefix)).length

Solution

  1. Step 1: Understand case sensitivity issue

    Direct startsWith is case sensitive, so 'Test' and 'test' differ.
  2. Step 2: Use toLowerCase() to normalize

    Convert both word and prefix to lowercase before checking startsWith to ignore case.
  3. Final Answer:

    words.filter(w => w.toLowerCase().startsWith(prefix.toLowerCase())).length -> Option A
  4. Quick Check:

    Normalize case before prefix check [OK]
Hint: Convert both strings to lowercase before startsWith [OK]
Common Mistakes:
  • Ignoring case sensitivity
  • Using includes instead of startsWith
  • Using endsWith instead of startsWith
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