Skip to the page

Coding for testers · Build it

Count each character in a string

The 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

  1. Why LinkedHashMap and not HashMap?
  2. What are the time and space costs?
  3. Now print only the characters that repeat.
  4. Find the first character that doesn't repeat.
  5. Do it with streams.
  6. What about emoji or Hindi text?
  7. How would you test your method?

The answer

What a strong answer covers

  • Loop over the lower-cased characters, skip whitespace (Character.isWhitespace), and map.merge(c, 1, Integer::sum) into a LinkedHashMap<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 char is 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 voice

Practise 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.

Start your free interview