Count Character Frequency
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
Case-sensitive
All same char
Empty string
z not found
l appears twice
Algorithm Flow
Solution Approach
Iterate through the string and update character counts in a map.
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
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
