← Questions

Generator for substring pattern matches

0
AppleCodingLast asked Dec 2025

A coding interview question asked in Apple's technical phone screen, last asked Dec 2025. It tests strings, generators and pattern matching.

Write a generator that scans a string s from left to right and yields once for every occurrence of a non-empty pattern. Occurrences may overlap. The scan must stay linear in the worst case.

Interface

Unless you agree on a different interface with the interviewer, assume (Python):

  • matches(s: str, pattern: str) -> Iterator[bool]: yields True once per occurrence, in order, as soon as the scan reaches the end of that occurrence.

Example

list(matches("aaaa", "aa"))       ->  [True, True, True]   # at 0, 1 and 2
list(matches("abababa", "aba"))   ->  [True, True, True]   # at 0, 2 and 4
list(matches("abc", "d"))         ->  []

Constraints

  • 0 <= len(s) <= 10^6, 1 <= len(pattern) <= 10^5
  • Target O(len(s) + len(pattern)) time.

Clarifying questions

  • Do overlapping matches count?
  • Should it yield the start index instead of True?
  • Can s arrive as a stream of characters rather than a full string?

What a strong answer covers

  • The naive check at each index and why it is O(n × m) on inputs like "aaaa…" with "aaa…b".
  • KMP: the failure table for the pattern, and a scan that falls back on a mismatch and after each match (which is what keeps overlaps).
  • Why a generator fits: it emits matches lazily and works with a character stream.
  • Tests: overlapping matches, pattern longer than s, empty s, the whole string as the pattern.

Follow-ups

  • Yield the start index of each match.
  • Match several patterns at once (Aho-Corasick).
  • Rolling hash (Rabin-Karp) as an alternative, and how to handle collisions.

Where it's asked

  • Apple · Technical phone screen · Last asked Dec 2025

What it tests

strings · generators · pattern matching

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding