Stream Data Processing with Early Cutoff on Sequence Detection
StringsModel answerLast 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_generatoryields["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_generatoryields["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_sequenceis 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?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The core challenge of this problem is balancing two competing requirements:
- Never emit characters that turn out to be part of the
stop_sequence. - Never hold back characters longer than necessary (avoid unnecessary buffering and memory growth).
At any given point in the stream, the only characters we must hold back are those forming the longest suffix of the text seen so far that is also a prefix of stop_sequence. Notice that these held-back characters are always a prefix of stop_sequence. Thus, rather than maintaining a separate growing string buffer, we only need to keep track of a single integer state: matched_count, representing how many characters of stop_sequence are currently tentatively matched. The buffered string itself is implicitly stop_sequence[:matched_count].
We can maintain this state efficiently using the Knuth-Morris-Pratt (KMP) algorithm:
- Precompute the KMP failure table (LPS array) for
stop_sequencein $O(M)$ time. - Maintain
matched_countacross chunk boundaries. - For each incoming chunk, process characters one by one. If a mismatch occurs, use the failure table to fall back to the next longest valid prefix state.
- If
matched_countreaches $M$ (length ofstop_sequence), we have encountered the complete sequence. Yield any preceding text from the current chunk/buffer and return immediately. - If the chunk ends without completing a full match, yield any characters that were previously held back but are no longer part of the current prefix match state.
If the generator is exhausted while matched_count > 0, the partial match was a false alarm at the end of the stream, so we flush stop_sequence[:matched_count].
Python 3 Implementation
def stream_until_sequence(chunk_generator, stop_sequence):
"""
Yields string segments from chunk_generator until stop_sequence is encountered.
Memory usage is bounded by O(M) where M is len(stop_sequence).
"""
m = len(stop_sequence)
if m == 0:
return
# Step 1: Precompute KMP failure table (Longest Prefix Suffix array)
lps = [0] * m
prev_lps = 0
for i in range(1, m):
while prev_lps > 0 and stop_sequence[i] != stop_sequence[prev_lps]:
prev_lps = lps[prev_lps - 1]
if stop_sequence[i] == stop_sequence[prev_lps]:
prev_lps += 1
lps[i] = prev_lps
def reconstruct_prefix(pending_len, chunk, target_len):
"""
Helper to construct the first target_len characters combining
the previously held-back prefix stop_sequence[:pending_len] and chunk.
"""
if target_len <= pending_len:
return stop_sequence[:target_len]
return stop_sequence[:pending_len] + chunk[:target_len - pending_len]
matched = 0 # Number of characters of stop_sequence currently matched
for chunk in chunk_generator:
if not chunk:
continue
pending = matched
for idx, char in enumerate(chunk):
while matched > 0 and char != stop_sequence[matched]:
matched = lps[matched - 1]
if char == stop_sequence[matched]:
matched += 1
if matched == m:
# Complete match found at chunk[idx]
# Total available chars in current view = pending + (idx + 1)
# Chars to yield = Total available - length of match (m)
emit_len = pending + idx + 1 - m
out = reconstruct_prefix(pending, chunk, emit_len)
if out:
yield out
return
# End of chunk reached without full match.
# Total chars in view = pending + len(chunk)
# We must keep 'matched' chars held back; emit the rest.
emit_len = pending + len(chunk) - matched
out = reconstruct_prefix(pending, chunk, emit_len)
if out:
yield out
# If stream ends with a partial match, flush the remaining held-back characters
if matched > 0:
yield stop_sequence[:matched]
Complexity Analysis
- Time Complexity:
- Building the KMP failure table takes $O(M)$ time where $M = \text{len}(stop_sequence)$.
- Processing $N$ characters across all stream chunks takes $O(N)$ amortized time, because the
matchedcounter is incremented at most once per character and decremented via the LPS array at most as many times as it was incremented. - Overall Time Complexity: $\mathcal{O}(M + N)$.
- Space Complexity:
- $\mathcal{O}(M)$ auxiliary space to store the failure table of size $M$.
- No stream buffer of size $N$ is maintained, fulfilling the $O(M)$ constraint.
Common Pitfalls & Edge Cases
- Naïve Reset on Mismatch: Resetting the match counter to
0on a character mismatch (e.g., matching"aab"against"aaab") fails to account for overlapping prefixes. Using the KMP failure table correctly handles overlapping occurrences. - Memory Leaks / Unbounded Buffers: Accumulating chunks into a single large buffer string until
stop_sequenceappears violates the $O(M)$ space requirement and causes high memory consumption on long streams. - Stream Exhaustion during Partial Match: If the stream ends while a partial match is active (e.g., stream ends with
"ta"when searching for"tag"), failing to yield the buffered"ta"results in data loss.