Code Logo

Count Character Frequency

Published at25 Jul 2026
Easy 0 views
Like0

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
Recommendation Algorithm Flow for Count Character Frequency

Solution Approach

function solution(s, c) {
  var count = 0;
  for (var i = 0; i < s.length; i++) {
    if (s.charAt(i) === c) count++;
  }
  return count;
}

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;
    }
}