Count occurrences of a word in a given string
Filed under Adobe
Free read 3 of 3Determine 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
Determine if overlapping matches should be counted separately.
Iterate through every possible starting index in the text and check slice equality with the target word.
Use built-in string find methods in a loop advancing by 1 to catch overlapping matches, or KMP/Rabin-Karp for larger texts.
Word longer than text, empty text or word.
Solution
O(N * M) time, O(1) space
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.