KatInterview

Stream Data Processing with Early Cutoff on Sequence Detection

StringsModel answer
MediumModel answerStringsstringssliding-windowtwo-pointers

Last updated

Yield data from a continuous stream of string fragments, terminating immediately when a specific multi-character sequence is identified across fragment boundaries.

You are tasked with building a stream processing utility that receives a sequence of string chunks from an iterator or generator. Your utility must continuously yield text output while checking for a specific multi-character sequence (stop_sequence).

As soon as the target stop_sequence is completed in the incoming data stream, the process must halt. Any characters that belong to the matching stop_sequence must not be emitted. If a partial prefix of the stop sequence appears at the end of a chunk, that prefix must be held back until you can confirm whether the sequence continues or breaks. If the stream ends without completing the stop_sequence, all held-back characters must be yielded before finishing.

Write a function with the following interface:

def stream_until_sequence(chunk_generator, stop_sequence):
    """
    chunk_generator: An iterator yielding string fragments.
    stop_sequence: The target string pattern that triggers early termination.
    Yields: Processed text blocks, stopping before the first complete match of stop_sequence.
    """

Examples

Example 1:

  • Input: chunk_generator yields ["alpha", "betagamma", "delta"], stop_sequence = "tag"
  • Output: "alpha", "be"
  • Explanation: The substring "tag" starts near the end of "beta" (character 't') and completes inside "gamma" (characters "ag"). The function outputs "alpha" and "be", then immediately terminates without processing the remainder of "gamma" or "delta".

Example 2:

  • Input: chunk_generator yields ["data_", "stream"], stop_sequence = "xyz"
  • Output: "data_", "stream"
  • Explanation: The target sequence is never encountered, so all chunks are yielded in full.

Requirements & Constraints

  • The length of stop_sequence is at least 1.
  • Incoming chunk sizes can vary arbitrarily (some may be smaller than stop_sequence, others much larger).
  • Additional memory usage must remain $O(M)$, where $M$ is the length of stop_sequence.
  • The stop pattern can cross an arbitrary number of chunk boundaries.

Hints

Hint 1

Consider how to safely emit text without over-buffering. What is the minimum number of characters you must withhold at any given moment?

Hint 2

A partial match at the tail of one chunk might prove to be a false alarm in the next chunk. How do you recover held-back characters when a match fails?

Hint 3

Think about string matching algorithms like Knuth-Morris-Pratt (KMP). How can carrying a state integer across chunks allow you to process streaming input in linear time and $O(M)$ auxiliary space?