Count Character Frequency
Published at25 Jul 2026
Created by M Ichsanul Fadhil
Given a string and a character, count how many times the character appears in the string. The search is case-sensitive (uppercase and lowercase are different).
Iterate through each character of the string and compare it with the target character. Increment a counter for each match. Return the final count.
This is a fundamental string counting problem with O(n) time complexity and O(1) space. The character comparison should use the language's equality operator.
Edge cases include empty strings (count is 0), character not present (count is 0), case sensitivity, and multiple occurrences of the same character.
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
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
