KatInterview

Count Case-Sensitive Occurrences in a Text

StringsAuto-graded · 23 test cases
EasyAuto-gradedStringsstringscountingsubstring

Last updated

Count how many times a target character, or substring, appears in a text under case-sensitive, non-overlapping matching.

Write a function that reports how many times a target appears inside a piece of text.

You are given two strings, text and target. Return the number of non-overlapping occurrences of target in text, scanning from left to right.

Rules:

  • Matching is case-sensitive: "t" and "T" are different characters.
  • Usually target is a single character, and the answer is simply how many times that character appears in text.
  • If target is longer than one character, treat it as a substring and count its non-overlapping occurrences. When the whole target never appears in text, the answer is 0.
  • If target is the empty string, return len(text) + 1.
  • Return an integer.

Constraints

  • text and target are Python strings and may contain letters, digits, spaces and punctuation.
  • 0 <= len(text) <= 10^5
  • 0 <= len(target) <= 10^5
  • No input validation or exceptions are required.

Examples

Example 1

Input: count_symbol_occurrences('Today is Tuesday', 't')

Output: 0

Example 2

Input: count_symbol_occurrences('This is the first message', 'Hello this is the second message')

Output: 0

Example 3

Input: count_symbol_occurrences('Hello, hello!', 'l')

Output: 4

Hints

Hint 1

For a single-character target, one pass over the text with a counter is enough.

Hint 2

Because a longer target must be matched as a whole substring, comparing character by character is not enough. Check whether the slice of text at each position equals the target.

Hint 3

After a match of a longer target, continue scanning after the end of that match so occurrences never overlap. Python's built-in string counting does exactly this.