Challenge - 5 Problems
Frequency Counter Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of frequency count using unordered_map
What is the output of the following C++ code that counts character frequencies in a string?
DSA C++
std::string s = "banana"; std::unordered_map<char, int> freq; for (char c : s) { freq[c]++; } for (auto &pair : freq) { std::cout << pair.first << ":" << pair.second << " "; }
Attempts:
2 left
💡 Hint
Remember unordered_map does not guarantee order, but the counts are fixed.
✗ Incorrect
The string "banana" has 1 'b', 3 'a's, and 2 'n's. The output prints each character and its count. The order may vary but the counts must match.
🧠 Conceptual
intermediateFrequency Counter Pattern Purpose
What is the main purpose of the frequency counter pattern using a hash map in algorithms?
Attempts:
2 left
💡 Hint
Think about what a hash map stores and how it helps count.
✗ Incorrect
Frequency counter pattern uses a hash map to store elements as keys and their counts as values, enabling quick frequency lookup.
🔧 Debug
advancedIdentify the error in frequency counting code
What error does the following C++ code produce when counting frequencies of integers in a vector?
std::vector nums = {1, 2, 2, 3};
std::unordered_map freq;
for (int i = 0; i < nums.size(); i++) {
freq[nums[i]] = freq[nums[i]] + 1;
}
std::cout << freq[4];
DSA C++
std::vector<int> nums = {1, 2, 2, 3}; std::unordered_map<int, int> freq; for (int i = 0; i < nums.size(); i++) { freq[nums[i]] = freq[nums[i]] + 1; } std::cout << freq[4];
Attempts:
2 left
💡 Hint
Consider how unordered_map behaves when accessing a key that does not exist.
✗ Incorrect
Accessing freq[4] inserts key 4 with default value 0, so printing freq[4] outputs 0 without error.
🚀 Application
advancedUsing frequency counter to check anagrams
Which code snippet correctly uses a frequency counter hash map to check if two strings are anagrams?
Attempts:
2 left
💡 Hint
Anagrams have the same character counts, so decrementing counts and checking negatives helps.
✗ Incorrect
Option A increments counts for s1, then decrements for s2, returning false if any count goes negative, ensuring exact match.
❓ Predict Output
expertOutput of frequency counter with nested loops and map
What is the output of this C++ code that counts frequencies of integers and prints keys with frequency > 1?
DSA C++
std::vector<int> nums = {1, 2, 2, 3, 3, 3, 4}; std::map<int, int> freq; for (int num : nums) { freq[num]++; } for (auto &pair : freq) { if (pair.second > 1) { std::cout << pair.first << ":" << pair.second << " "; } }
Attempts:
2 left
💡 Hint
Only print numbers with frequency greater than 1, and map orders keys ascending.
✗ Incorrect
Numbers 2 and 3 appear more than once with counts 2 and 3 respectively. Map prints keys in ascending order.
