← Adobe questions

Count occurrences of a word in a given string

Filed under Adobe

Free read 3 of 3

Determine if overlapping matches should be counted separately.

The question

Count how many times a specific target word appears as a distinct substring or word within a given string.

Constraints

  • 1 <= string.length <= 10^4
  • 1 <= word.length <= string.length

Examples

Input
text = "ababab", word = "aba"
Output
2
Why
"aba" appears starting at index 0 and index 2 (overlapping instances depending on exact problem definition, typically substring counts).

Approach

  1. Determine if overlapping matches should be counted separately.

Solution

O(N * M) time, O(1) space

Python
class Solution:
    def countOccurrences(self, text: str, word: str) -> int:
        if not word or not text or len(word) > len(text):
            return 0
        count = 0
        idx = text.find(word)
        while idx != -1:
            count += 1
            idx = text.find(word, idx + 1)
        return count

Tips

  • What they are testing: Test with words longer than the text, strings without the word, and overlapping occurrences.
  • Common mistake: Using non-overlapping search when overlapping occurrences are expected, or vice versa.

Related Adobe questions

Collected from public candidate posts and coding forums. Updated Nov 2026.