Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Count Substring Occurrences

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Count Substring Occurrences. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Airtel Digital services may scan message text for repeated routing, campaign, or support patterns. Given a text string and a non-empty pattern string, return how many times the pattern occurs in the text, including overlapping occurrences.

Formal Specification

Implement count_substring_occurrences(text, pattern).

  • text is a string containing the message to scan.
  • pattern is a non-empty string to search for.
  • Return an integer representing the number of valid starting positions where pattern matches a substring of text.
  • Matching is case-sensitive, and occurrences may overlap.

The expected solution should run in linear time using the Knuth-Morris-Pratt pattern-matching technique.

Constraints

  • 0 <= len(text) <= 10^6
  • 1 <= len(pattern) <= 10^5
  • Both strings contain standard Unicode characters
  • Matching is case-sensitive
  • The pattern is guaranteed to be non-empty

Function Signature

def count_substring_occurrences(text, pattern):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output