Challenge - 5 Problems
Prefix Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of prefix count function with simple input
What is the output of the following JavaScript code that counts words starting with a given prefix?
DSA Javascript
function countWordsWithPrefix(words, prefix) {
let count = 0;
for (const word of words) {
if (word.startsWith(prefix)) {
count++;
}
}
return count;
}
const words = ['apple', 'app', 'application', 'banana', 'apex'];
console.log(countWordsWithPrefix(words, 'app'));Attempts:
2 left
💡 Hint
Count how many words start exactly with 'app'.
✗ Incorrect
The words starting with 'app' are 'apple', 'app', and 'application', so the count is 3.
🧠 Conceptual
intermediate1:30remaining
Understanding prefix matching in strings
Which of the following statements correctly describes how to check if a word starts with a given prefix in JavaScript?
Attempts:
2 left
💡 Hint
Think about the method that checks the start of a string.
✗ Incorrect
The startsWith() method returns true if the string begins with the specified prefix.
🔧 Debug
advanced2:00remaining
Identify the error in prefix counting code
What error will the following code produce when run, and why?
DSA Javascript
function countPrefix(words, prefix) {
let count = 0;
for (let i = 0; i <= words.length; i++) {
if (words[i].startsWith(prefix)) {
count++;
}
}
return count;
}
console.log(countPrefix(['cat', 'car', 'dog'], 'ca'));Attempts:
2 left
💡 Hint
Check the loop condition and array indexing.
✗ Incorrect
The loop uses i <= words.length which causes words[words.length] to be undefined, so calling startsWith on undefined throws a TypeError.
🚀 Application
advanced2:00remaining
Count words with prefix ignoring case
Which code snippet correctly counts words starting with a prefix ignoring case differences?
Attempts:
2 left
💡 Hint
Convert both word and prefix to the same case before checking.
✗ Incorrect
To ignore case, convert both strings to lower (or upper) case before using startsWith.
🧠 Conceptual
expert1:30remaining
Time complexity of counting words with prefix
What is the time complexity of counting how many words start with a given prefix in a list of n words, each of average length m?
Attempts:
2 left
💡 Hint
Consider how many words and how many characters per word are checked.
✗ Incorrect
Each of the n words is checked for prefix of length up to m, so total is O(n * m).