← Intuit questions

Count Occurrences of Word in Sentence

Filed under Intuit

Free read 3 of 3

Define if the search is case-sensitive and how punctuation or whitespace should be handled.

The question

Write a function to count the exact occurrences of a target word within a given sentence string, ensuring proper handling of punctuation and word boundaries.

Constraints

  • Sentence length is between 0 and 10^5 characters.
  • Target word contains only alphanumeric characters.
  • Case-insensitive matching should be handled robustly.

Examples

Input
sentence = "Intuit is a great fintech company, and Intuit hires software engineers.", target = "Intuit"
Output
2
Why
The word "Intuit" appears twice, ignoring punctuation attached to the comma.

Approach

  1. Define if the search is case-sensitive and how punctuation or whitespace should be handled.

Solution

O(N) time, O(N) space

Python
import re

class Solution:
    def countWord(self, sentence: str, target: str) -> int:
        if not sentence or not target:
            return 0
        pattern = r'\b' + re.escape(target) + r'\b'
        return len(re.findall(pattern, sentence, re.IGNORECASE))

Tips

  • What they are testing: Test with empty strings, punctuation attached to words, multiple spaces, and case variations.
  • Common mistake: Using a simple substring search (like indexOf) which matches the target inside other words, rather than enforcing word boundaries.

Related Intuit questions

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