00:00

Problem Statement

Input/Output Examples

Visual Explanation

Each character is looked up in the map once. merge(c, 1, Integer::sum) inserts 1 for a new key or adds 1 to the existing value, so one line handles both cases.

Approaches

Both approaches build the same map. One uses a plain loop, the other a stream collector.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of the string and k is the number of distinct characters, which is at most n. Each map update takes O(1) time on average.

Interview Tips and Recommended Approach

  • Choose the map deliberately. Say why you use LinkedHashMap (first-seen order) instead of HashMap (no order) or TreeMap (sorted order).
  • Know merge() and getOrDefault(). Both replace the old if (map.containsKey(c)) pattern with one clear line.
  • Mention the array alternative. For lowercase letters only, an int[26] counter is faster and uses fixed memory.
  • Ask about case and spaces. Clarify whether A and a are the same and whether spaces should be counted.

Recommended Approach: LinkedHashMap With merge()

Why: it runs in one pass, keeps the output order predictable and works for any character, not just letters. The merge() call keeps the code short without hiding what happens.