Stream output until stop token appears
MicrosoftSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to process streaming data from a generator while detecting a multi-character stop sequence that may be split across data chunks.
Problem Statement
You are tasked with building a stream processor that reads chunks of text from a generator. Your goal is to yield the processed text until you encounter a specific 'stop token' string.
Once the stop token is found, the function must terminate immediately. Any part of the stop token that was partially matched at the end of a chunk should not be emitted. If the stop token never appears, yield all data from the stream.
Implement the following function:
def stream_until_stop(data_generator, stop_token):
"""
data_generator: A generator that yields strings (chunks).
stop_token: The string sequence that triggers termination.
Yields: Parts of the string until the stop_token is encountered.
"""
Examples
Example 1:
- Input:
data_generatoryields['abc', 'defg', 'hi'],stop_token='ef' - Output:
'abc', 'd' - Explanation: The stop token 'ef' starts at the end of the first chunk 'abc' (none) and continues into 'defg'. The function yields 'abc' and 'd', then stops.
Example 2:
- Input:
data_generatoryields['hello', ' world'],stop_token='xyz' - Output:
'hello', ' world'
Constraints
stop_tokenlength will be at least 1.- Chunks can be of arbitrary length.
- Your solution should use O(M) space, where M is the length of the
stop_token.
Edge Cases
- The stop token is split across three or more chunks.
- The stop token is longer than a single chunk.
- The stream contains multiple occurrences of the stop token (stop at the first one).
Hints
Hint 1
Maintain a buffer that stores the suffix of the current string that could potentially be the start of the stop token.
Hint 2
For each chunk, search for the stop token in the concatenation of the buffer and the new chunk.
Hint 3
If the stop token is found, yield the portion of the chunk leading up to the start of the token and terminate; otherwise, carefully manage what remains in your buffer for the next iteration.
Follow-up questions
- How would you modify this if the stop token were a complex regex pattern instead of a literal string?
- What are the implications for memory usage if the stream is extremely fast but the stop token is very long?
- How would you implement a 'look-ahead' feature to ensure you don't buffer more than necessary?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.