Count Single-Character Occurrences in a String
StringsAuto-graded · 18 test casesLast updated
Tests whether a candidate can scan a string and tally exact, case-sensitive matches for a given character, including edge cases like empty input and repeated characters.
Count Single-Character Occurrences in a String
Implement count_char_occurrences(text, target).
textis the string to search through.targetis a single character you need to count.
Return the total number of times target appears in text.
Matching rules:
- Comparison is case-sensitive:
'A'and'a'are treated as different characters. - Every matching position counts, even when the same character appears multiple times in a row.
- If
textcontains no match — including whentextis an empty string — return0.
The return value is a single integer representing the full answer.
Constraints
0 <= len(text) <= 10^5len(target) == 1- Both
textandtargetconsist of printable ASCII characters. - Do not normalize or transform the case of either argument before comparing.
Examples
Example 1
Input: count_char_occurrences('hello', 'l')
Output: 2
Example 2
Input: count_char_occurrences('Discord', 'd')
Output: 1
Example 3
Input: count_char_occurrences('banana', 'a')
Output: 3
Example 4
Input: count_char_occurrences('Python', 'z')
Output: 0
Hints
Hint 1
A single pass through the string is all you need — check each character one at a time and keep a running total.
Hint 2
Python's built-in string methods include one that counts non-overlapping occurrences of a substring; for a length-1 target, every match is non-overlapping by definition.
Hint 3
Make sure your comparison is exact: 'D' and 'd' should never match each other, so avoid any .lower() or .upper() calls.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core task is to walk through every position in text and check whether the character there equals target. Because each position is either a match or it isn't, a single linear pass is both necessary and sufficient — you can't skip any position without risking a missed match.
Idiomatic solution — str.count
Python's built-in str.count(sub) does exactly this scan internally. When sub is a single character, the "non-overlapping" constraint it imposes has no effect (a one-character window can never overlap with itself), so it counts every matching position precisely once. It returns 0 naturally when there are no matches and when the string is empty. This is the clearest and fastest way to express the solution.
def count_char_occurrences(text: str, target: str) -> int:
return text.count(target)
Manual loop — same logic made explicit
If asked to avoid built-ins, the equivalent loop makes the reasoning transparent:
def count_char_occurrences(text: str, target: str) -> int:
total = 0
for ch in text:
if ch == target:
total += 1
return total
At each step, ch == target is a code-point comparison, which is inherently case-sensitive ('D' == 'd' is False). The counter only increments on an exact match, so adjacent repeats each add 1 independently.
Why it handles every edge case
| Scenario | Behavior |
|---|---|
Empty text | The loop body never executes; returns 0 |
target absent | Counter stays at 0 throughout |
Case mismatch ('D' vs 'd') | == returns False; no increment |
Consecutive repeats ("aaa") | Each position checked independently; all counted |
Whitespace or punctuation as target | Treated as ordinary characters; works unchanged |
Complexity
- Time: O(n), where n =
len(text). Every character must be inspected at least once, so O(n) is optimal. - Space: O(1). Only a single integer counter is maintained; no copies or auxiliary structures are created.
When to reach for something else
If you need counts for many different characters on the same fixed string, build a collections.Counter once in O(n) and answer each query in O(1). For range queries ("how many times does target appear between index l and r?"), a per-character prefix-sum array gives O(1) per query after O(n) preprocessing. Neither is needed here.
def count_char_occurrences(text: str, target: str) -> int:
"""
Count how many times the single character `target` appears in `text`.
Matching is case-sensitive: uppercase and lowercase forms are distinct.
Every occurrence is counted, including consecutive repeats.
Returns 0 when there are no matches or when `text` is empty.
Parameters
----------
text : the string to search
target : a single character to look for
Returns
-------
int : number of times `target` appears in `text`
Time: O(n), where n = len(text)
Space: O(1)
"""
return text.count(target)