16. Count the Occurrences of a Character

Difficulty:EasyPattern:Character CountingTime:O(n)Space:O(1)

Given a string and a target character, count how many times the character appears.

How It Works & Algorithmic Design

Use a simple counting traversal:

  1. Initialize count = 0.
  2. Visit every character in the string.
  3. Compare it with the target character.
  4. Increment the counter when they match.
  5. Return the final count.

Why This Approach Works Best

Every character may contribute to the result, so the entire string must be inspected. The algorithm uses $O(n)$ time and $O(1)$ additional space.

Example Walkthrough
Input: String="banana", Target="a"
The character a appears multiple times.
Trace: b -> a(count=1) -> n -> a(count=2) -> n -> a(count=3)
The counter increments only for matching characters.
Output: 3
The character a appears three times.

Answer: Count a character

function countCharacter(str, target) {
  let count = 0;
  for (const char of str) {
    if (char === target) count++;
  }
  return count;
}
💡 Traverse every character and increment the counter whenever it matches the target.
Key Takeaways
  • Character counting is a direct application of the accumulator pattern.
  • Every character must be checked.
  • The algorithm uses O(n) time and O(1) extra space.