Challenge - 5 Problems
Character Frequency Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of character frequency count in a string
What is the output of the following JavaScript code that counts character frequencies in a string?
DSA Javascript
const str = "hello world"; const freq = {}; for (const ch of str) { freq[ch] = (freq[ch] || 0) + 1; } console.log(freq);
Attempts:
2 left
💡 Hint
Count each character carefully, including spaces.
✗ Incorrect
The code iterates over each character in the string and counts how many times it appears. The letter 'l' appears 3 times and 'o' appears 2 times, including the space character counted once.
❓ Predict Output
intermediateCharacter frequency count with case sensitivity
What is the output of this code that counts characters in a case-sensitive way?
DSA Javascript
const str = "AaBbAa"; const freq = {}; for (const ch of str) { freq[ch] = (freq[ch] || 0) + 1; } console.log(freq);
Attempts:
2 left
💡 Hint
Uppercase and lowercase letters are counted separately.
✗ Incorrect
The code counts 'A' and 'a' as different characters. 'A' appears twice, 'a' appears twice, 'B' once, and 'b' once.
🔧 Debug
advancedIdentify the error in character frequency counting code
What error will this code produce when run?
DSA Javascript
const str = "test"; const freq = new Map(); for (const ch of str) { freq[ch] = (freq[ch] || 0) + 1; } console.log(freq);
Attempts:
2 left
💡 Hint
Check how Map objects are accessed and updated.
✗ Incorrect
Map objects do not support bracket notation for setting keys. Using freq[ch] does not update the Map. The Map remains empty.
❓ Predict Output
advancedCorrect character frequency count using Map
What is the output of this code that correctly counts character frequencies using a Map?
DSA Javascript
const str = "banana"; const freq = new Map(); for (const ch of str) { freq.set(ch, (freq.get(ch) || 0) + 1); } console.log(Object.fromEntries(freq));
Attempts:
2 left
💡 Hint
Use Map's get and set methods properly.
✗ Incorrect
The code uses Map methods correctly to count characters. 'b' appears once, 'a' three times, 'n' twice.
🧠 Conceptual
expertTime complexity of character frequency counting
What is the time complexity of counting character frequencies in a string of length n using a hash map or object in JavaScript?
Attempts:
2 left
💡 Hint
Consider how many times each character is visited and the cost of updating counts.
✗ Incorrect
Each character is visited once, and updating the count in a hash map is O(1) on average, so total time is O(n).
