Code Logo

Count Character Frequency

Published at25 Jul 2026
Easy 1 views
Like0

Given a string, count how many times each character appears. Return an object/map where keys are characters and values are their frequencies.

For example, "hello" has frequencies: h=1, e=1, l=2, o=1. "aabb" has a=2, b=2. An empty string returns an empty map.

Character frequency counting is one of the most fundamental string processing tasks. It is the foundation for anagram checking, palindrome validation, word games, and cryptography. The solution uses a hash map to store character counts in a single pass.

The solution iterates through each character, retrieves its current count from the map (defaulting to 0 if not present), increments it, and stores it back. After processing all characters, the map contains the complete frequency distribution.

Edge cases include an empty string (return empty map), a string with all unique characters (each count is 1), and case-sensitive counting where 'A' and 'a' are different characters.

Example Input & Output

Example 1
Input
"Test","t"
Output
1
Explanation

Case-sensitive

Example 2
Input
"aaaa","a"
Output
4
Explanation

All same char

Example 3
Input
"","x"
Output
0
Explanation

Empty string

Example 4
Input
"hello","z"
Output
0
Explanation

z not found

Example 5
Input
"hello","l"
Output
2
Explanation

l appears twice

Algorithm Flow

Recommendation Algorithm Flow for Count Character Frequency

Solution Approach

Iterate through the string and update character counts in a map.

function charFreq(s)
  freq = empty map
  for i = 0 to length(s) - 1
    c = s[i]
    freq[c] = (freq[c] or 0) + 1
  return freq

Create an empty map. Loop through each character. For each character, get its current count (defaulting to 0), increment it, and store the result back in the map. Return the completed frequency map.

Time complexity is O(n), space complexity is O(k) where k is the number of unique characters.

Best Answers

java
class Solution {
    public int solution(String s, char c) {
        int r=0;for(int i=0;i<s.length();i++){if(s.charAt(i)==c)r++;}return r;
    }
}