Coding for testers · Build it
Count each character in a string
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
Write a Java method that counts how many times each character appears in a string, ignoring spaces and case, and prints the counts in the order the characters first appear. For 'Test Automation', the output starts t=4, e=1, s=1, a=2.
Then
Follow-ups the interviewer asks next
- Why
LinkedHashMapand notHashMap? - What are the time and space costs?
- Now print only the characters that repeat.
- Find the first character that doesn't repeat.
- Do it with streams.
- What about emoji or Hindi text?
- How would you test your method?
The answer
What a strong answer covers
- Loop over the lower-cased characters, skip whitespace (
Character.isWhitespace), andmap.merge(c, 1, Integer::sum)into aLinkedHashMap<Character, Integer>, which keeps first-seen order. - O(n) time; O(k) space for k distinct characters.
- Repeating characters: entries with a count above 1. First non-repeating: the first entry with a count of 1, thanks to the linked map's order.
- Streams:
s.toLowerCase().chars().filter(c -> !Character.isWhitespace(c)).mapToObj(c -> (char) c).collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())). - Unicode: a Java
charis one UTF-16 unit; emoji need code points (codePoints()), and a Hindi letter with a vowel sign is several code points. - Tests: empty string, null (agree on an exception or an empty result), only spaces, one character, mixed case, the example.
The red pen
Common traps
Avoid:nested loops (O(n²)) without saying so; a HashMap while claiming the order is kept; forgetting case or spaces; no thought for empty input.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.