Hint: Count each character carefully, watch repeated letters [OK]
Common Mistakes:
Counting 'l' only once
Confusing getOrDefault usage
Expecting syntax error incorrectly
4. Find the error in this Java code snippet for counting character frequency:
String s = "test";
Map freq = new HashMap<>();
for (int i = 0; i <= s.length(); i++) {
char c = s.charAt(i);
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
medium
A. Using <= in loop causes IndexOutOfBoundsException
B. HashMap cannot store Character keys
C. getOrDefault method is not available in HashMap
D. charAt method does not exist for String
Solution
Step 1: Analyze loop condition
Loop uses i <= s.length(), but valid indices are 0 to s.length()-1.
Step 2: Identify error consequence
Accessing s.charAt(s.length()) causes IndexOutOfBoundsException at runtime.
Final Answer:
Using <= in loop causes IndexOutOfBoundsException -> Option A
Quick Check:
Loop index must be less than length [OK]
Hint: Loop index must be less than string length, not equal [OK]
Common Mistakes:
Thinking HashMap can't store Character keys
Assuming getOrDefault is unavailable
Believing charAt doesn't exist for String
5. Given a string with mixed case letters, how can you count character frequencies ignoring case (treat 'A' and 'a' as same)? Choose the best approach.
hard
A. Ignore characters that are uppercase
B. Count uppercase and lowercase separately and add later
C. Use a TreeMap instead of HashMap
D. Convert string to lowercase before counting frequencies
Solution
Step 1: Understand case-insensitive counting
To treat 'A' and 'a' the same, convert all characters to one case.
Step 2: Choose best method
Converting entire string to lowercase before counting ensures all letters are uniform.
Final Answer:
Convert string to lowercase before counting frequencies -> Option D
Quick Check:
Uniform case simplifies frequency counting [OK]
Hint: Convert string to one case before counting [OK]
Common Mistakes:
Counting uppercase and lowercase separately
Using TreeMap which doesn't solve case issue
Ignoring uppercase letters incorrectly
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.