Count the Frequency of Each Character in a String
Count how many times each distinct character appears in a string.
Walk the string once and keep a map from character to count. For each character, use getOrDefault to read its current count and store that value plus one. A LinkedHashMap preserves the order characters first appear, so the output is stable and readable. This runs in O(n) time.
Problem Statement
Given a string, count how many times each distinct character appears and report
the result as character-to-count pairs. For example, in hello the character
l appears twice while h, e and o appear once.
Preserve the order in which characters first appear so the output is predictable. Count every character, including spaces, unless told otherwise.
Input: A single string s.
Output: Each distinct character mapped to its number of occurrences.
Examples
Input: "hello"
Output: {h=1, e=1, l=2, o=1}l appears twice; the other three characters appear once each.
Input: "aabbbc"
Output: {a=2, b=3, c=1}a twice, b three times, c once, in first-appearance order.
Constraints
0 <= s.length <= 10^5Preserve first-appearance order of characters
Think Before You Code
Reveal the questions to ask yourself first
- What data structure maps a character to a running count?
- How do you increment a count that might not exist yet?
- How do you keep the output in the order characters first appear?
- Should spaces and punctuation be counted too?
Hints
Open them one at a time — try after each before revealing the next.
Hint 1
Hint 2
Hint 3
Approach
Reveal the step-by-step approach
Build a frequency map in a single pass.
- Create a
LinkedHashMap<Character, Integer>to hold counts in first-seen order. - For each character
cin the string:- Read its current count with
map.getOrDefault(c, 0). - Store that count plus one back into the map.
- Read its current count with
- After the loop, the map holds every distinct character with its total count.
getOrDefault removes the need for a separate "does this key exist" check, and
LinkedHashMap keeps the printed order tied to when each character first appeared.
Dry Run
Walk through the example step by step
Counting characters in "hello":
char | map before | map after
-----+-------------------+---------------------------
h | {} | {h=1}
e | {h=1} | {h=1, e=1}
l | {h=1, e=1} | {h=1, e=1, l=1}
l | {h=1, e=1, l=1} | {h=1, e=1, l=2}
o | {h=1, e=1, l=2} | {h=1, e=1, l=2, o=1}
final: {h=1, e=1, l=2, o=1}
Solution
Reveal the full Java solution
import java.util.LinkedHashMap;
import java.util.Map;
public class CharFrequency {
public static Map<Character, Integer> frequency(String s) {
Map<Character, Integer> freq = new LinkedHashMap<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
return freq;
}
public static void main(String[] args) {
System.out.println(frequency("hello")); // {h=1, e=1, l=2, o=1}
System.out.println(frequency("aabbbc")); // {a=2, b=3, c=1}
}
}
Each character is looked up once and updated once, so the whole tally costs a
single pass. getOrDefault(c, 0) treats a missing key as zero, letting the same
line handle both the first sighting and every repeat. Printing a LinkedHashMap
produces {key=value, ...} in insertion order, matching the first-appearance
requirement. For a strictly ASCII input an int[256] array would also work.
O(n) where n is the string lengthSpace: O(k) where k is the number of distinct charactersCommon Mistakes
- Using a plain HashMap and being surprised the output order changes.
- Forgetting getOrDefault and getting a NullPointerException on the first occurrence.
- Assuming counts reset between characters instead of accumulating.
Edge Cases to Test
- An empty string returns an empty map {}.
- A single character returns that character with count 1.
- Repeated spaces are counted like any other character unless filtered out.
Interview Follow-Ups
- How would you print only the characters that appear more than once?
- How would you find the character with the highest frequency?
- How would you make the count case-insensitive?
Practising for Java interviews?
CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
Explore the Java Full Stack program →