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 Java code that counts character frequencies in the string "hello"?
DSA Java
import java.util.*; public class Main { public static void main(String[] args) { String s = "hello"; Map<Character, Integer> freq = new HashMap<>(); for (char c : s.toCharArray()) { freq.put(c, freq.getOrDefault(c, 0) + 1); } System.out.println(freq); } }
Attempts:
2 left
💡 Hint
Count how many times each letter appears in "hello".
✗ Incorrect
The letter 'l' appears twice, all others once.
🧠 Conceptual
intermediateUnderstanding character frequency counting approach
Which data structure is best suited to count the frequency of characters in a string efficiently?
Attempts:
2 left
💡 Hint
Think about direct indexing by character code.
✗ Incorrect
An array indexed by ASCII codes allows O(1) access to counts for each character.
🔧 Debug
advancedIdentify the error in character frequency counting code
What error does the following Java code produce when counting character frequencies?
String s = "abc";
Map freq = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
freq.put(c, freq.get(c) + 1);
}
System.out.println(freq);
Attempts:
2 left
💡 Hint
Check what happens when freq.get(c) is called for a character not yet in the map.
✗ Incorrect
freq.get(c) returns null initially, so null + 1 causes NullPointerException.
🚀 Application
advancedFind the most frequent character in a string
Given a string, which code snippet correctly finds the character with the highest frequency?
DSA Java
String s = "banana"; Map<Character, Integer> freq = new HashMap<>(); for (char c : s.toCharArray()) { freq.put(c, freq.getOrDefault(c, 0) + 1); } char maxChar = ' '; int maxCount = 0; // Which option correctly finds maxChar and maxCount?
Attempts:
2 left
💡 Hint
Check which loop and condition correctly track the max frequency.
✗ Incorrect
Option D iterates over unique chars and updates maxCount and maxChar correctly.
❓ Predict Output
expertOutput of character frequency counting with Unicode characters
What is the output of this Java code counting frequencies of Unicode characters in the string "aáa"?
DSA Java
import java.util.*; public class Main { public static void main(String[] args) { String s = "aáa"; Map<Character, Integer> freq = new HashMap<>(); for (char c : s.toCharArray()) { freq.put(c, freq.getOrDefault(c, 0) + 1); } System.out.println(freq); } }
Attempts:
2 left
💡 Hint
Remember that 'a' and 'á' are different characters in Unicode.
✗ Incorrect
The string has two 'a' characters and one 'á' character, counted separately.
