16. Count the Occurrences of a Character
Given a string and a target character, count how many times the character appears.
How It Works & Algorithmic Design
Use a simple counting traversal:
- Initialize
count = 0. - Visit every character in the string.
- Compare it with the target character.
- Increment the counter when they match.
- 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:
3The 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.