AlgoMaster Logo

Count Occurrence of a Character

Last Updated: June 7, 2026

easy
3 min read

Understanding the Problem

Return how many positions in s hold exactly the character c. The return value is a number, not a position or a boolean, so even a string with zero matches produces a valid answer of 0.

The comparison is case sensitive. A and a are stored as different codes, so only an exact match increases the count. If the string is empty, or the character never appears, the answer is 0.

A few cases test the logic. An empty string has nothing to scan, so the loop runs zero times and the count stays at 0. A string where every character matches gives a count equal to its length. A character that never appears, such as z in "abc", leaves the counter at 0. The same scan handles all three.

Key Constraints:

  • 0 <= s.length <= 1000 → The string can be empty, so the code must run cleanly when there is nothing to read. The upper bound is small, so a single linear pass is fast enough.
  • Case sensitive matching → A match requires the exact same character, so A and a are counted separately.

Approach 1: Linear Scan

Intuition

Counting requires looking at every character at least once, since any skipped character might be the one being counted. This is where counting differs from searching: a search can stop on its first hit, but a count has to continue, because a later position can still add to the total.

Keep a running counter that starts at zero. Visit each character in order, and every time the current character equals c, add one to the counter. At the end of the string, the counter holds the total number of matches. That counter is the only state needed, so this uses constant extra memory regardless of string length.

Algorithm

  1. Initialize a counter variable to 0.
  2. Loop over every character in the string from the first index to the last.
  3. If the current character equals c, increase the counter by one.
  4. After the loop ends, return the counter.

Example Walkthrough

1Index 0 is 'b', not 'a'. count stays 0.
0
i
b
1
a
2
n
3
a
4
n
5
a
1/6

Take s = "banana" and c = 'a'. Index 0 is b, which does not match, so the count stays at 0. Index 1 is a, the first match, so the count becomes 1. Index 2 is n, no match. Index 3 is a, so the count becomes 2. Index 4 is n, no match. Index 5 is a, so the count becomes 3. The scan has reached the end, so the answer is 3.

The scan never stops early. After the first match at index 1, it keeps going to catch the matches at indices 3 and 5.

3
count

Code