Learn
Exam

Count Substring Occurrences

Difficulty
STARTER

Problem

Given a string word and a substring target, write a function solution that returns the number of times target appears in word. Even if target appears overlapping in word, all occurrences should be counted. For example, if word = "aaaa" and target = "aa", then target appears 3 times in total, including overlapping parts, so the result is 3.


Constraints

  • The length of word is between 1 and 100 inclusive.
  • The length of target is between 1 and the length of word inclusive.
  • Both word and target consist only of lowercase English letters.

Test Case

Test Case Number word target return
1 "aaaa" "aa" 3
2 "ababab" "aba" 2
3 "abcabcabc" "abc" 3

Explanation for Test Case 1

  • When word = "aaaa" and target = "aa", the substring "aa" appears 3 times in total, including overlaps, so the return value is 3.

Explanation for Test Case 2

  • When word = "ababab" and target = "aba", the substring "aba" appears 2 times in total, including overlaps, so the return value is 2.

Explanation for Test Case 3

  • When word = "abcabcabc" and target = "abc", the substring "abc" appears 3 times in total, so the return value is 3.