Count Occurrences of Word in Sentence
Filed under Intuit
Free read 3 of 3Define 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
Define if the search is case-sensitive and how punctuation or whitespace should be handled.
Split the sentence by spaces and iterate through each token, cleaning punctuation and comparing to the target.
Use regular expressions with word boundaries for a concise and production-ready implementation.
Handle empty strings, null inputs, and sentences with no matching words gracefully.
Solution
O(N) time, O(N) space
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.