Count Substring Occurrences

Easy ⏱ 8 min 88% acceptance ★★★★☆ 4.2
Write count_occurrences(s, sub) that returns how many non-overlapping times sub appears inside s.

Examples

Example 1
Input
s = 'abababab', sub = 'ab'
Output
4
Explanation

'ab' occurs 4 times, non-overlapping.

Example 2
Input
s = 'aaaa', sub = 'aa'
Output
2
Explanation

Non-overlapping counting: positions 0-1 and 2-3, not 0-1, 1-2, 2-3.

Constraints

  • 1 <= len(sub) <= len(s)

Topics

StringsSubstring Search

Companies

MetaSalesforce

Hints

Hint 1

`str.count()` already counts non-overlapping occurrences.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.