Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Split String by Substring

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

Your question is Split String by Substring. 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

Hyundai MOBIS Alabama receives diagnostic strings containing repeated markers that separate individual vehicle records. Given a string text and a non-empty marker string pattern, split text at every non-overlapping occurrence of pattern.

Return the substrings between consecutive matches, excluding the marker itself. Preserve empty substrings caused by consecutive markers or markers at the beginning or end. Matches must be selected from left to right, and an occurrence cannot overlap a previously selected occurrence.

Formal Specification

  • Input: two strings, text and pattern, containing printable ASCII characters.
  • Output: a list of strings containing the sections of text between matches.
  • If pattern does not occur, return [text].
  • pattern is guaranteed to be non-empty.

For efficient matching, implement the search using the Knuth-Morris-Pratt prefix-function technique rather than repeatedly rescanning the text.

Constraints

  • 0 <= len(text) <= 10^6
  • 1 <= len(pattern) <= 10^5
  • len(pattern) <= len(text) is not guaranteed
  • Matching is case-sensitive
  • Occurrences are split from left to right without overlap

Function Signature

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