KatInterview

Count Single-Character Occurrences in a String

StringsAuto-graded · 18 test cases
EasyAuto-gradedStringsstringscountingcase-sensitivity

Last 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).

  • text is the string to search through.
  • target is 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 text contains no match — including when text is an empty string — return 0.

The return value is a single integer representing the full answer.

Constraints

  • 0 <= len(text) <= 10^5
  • len(target) == 1
  • Both text and target consist 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.