Multi-Consumer Iterator with Shared Buffering
Data Structure DesignAuto-graded · 19 test casesLast updated
Tests iterator protocols, lazy evaluation, and memory-efficient buffering for multiple independent consumers reading from a single source stream.
Problem Description
You are building a system that allows multiple independent consumers to read from a single input stream. Your task is to implement multi_reader_stream that simulates n independent iterators sharing one source.
The function receives:
values: a list representing the source streamn: the number of independent consumers (iterators) to createoperations: a list of operation names to performarguments: corresponding arguments for each operation
Each operation is performed on one of the n consumers, identified by an index from 0 to n-1.
Operations
-
"next"with argument[index]: advance consumerindexby one element and return that element. If the consumer has exhausted the stream, returnNone. -
"list"with argument[index]: consume all remaining elements from consumerindexand return them as a list. If the consumer is already exhausted, return an empty list[].
Buffering Requirements
Your implementation must be lazy and memory-efficient:
- The source stream is advanced only when a consumer needs an item not yet buffered
- Items are buffered only when needed by at least one consumer
- Once all
nconsumers have advanced past an item, it should be removed from the buffer - Memory usage should be proportional to the "lag" (maximum difference in position between the fastest and slowest consumer), not the total stream size
Constraints
0 ≤ n ≤ 1000 ≤ len(values) ≤ 10,0001 ≤ len(operations) ≤ 1,000len(operations) == len(arguments)- Each operation references a valid consumer index:
0 ≤ index < n - All elements in
valuesare integers - Operations are either
"next"or"list"
Examples
Example 1
Input: multi_reader_stream([1, 2, 3], 2, ['list', 'list'], [[0], [1]])
Output: [[1, 2, 3], [1, 2, 3]]
Example 2
Input: multi_reader_stream([1, 2, 3, 4], 2, ['next', 'list', 'next'], [[0], [1], [0]])
Output: [1, [1, 2, 3, 4], 2]
Example 3
Input: multi_reader_stream([7, 8], 3, ['list', 'list', 'list'], [[0], [1], [2]])
Output: [[7, 8], [7, 8], [7, 8]]
Hints
Hint 1
Think about what information each consumer needs to track: just its current position in the stream is sufficient if you maintain a shared buffer correctly
Hint 2
The buffer should only contain items between the slowest and fastest consumer positions. After each operation, compute the minimum position across all consumers to determine what can be safely removed
Hint 3
Consider using a deque for the buffer since you'll be adding items at the back and removing from the front as consumers advance
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is maintaining multiple independent read positions over a single source while keeping memory bounded. We achieve this through shared buffering with position tracking.
Key components:
-
Shared buffer: A
dequeholds items that have been pulled from the source but not yet consumed by all readers. We trackbase, the absolute stream position of the first buffered item. -
Per-consumer positions: An array
positions[i]stores the absolute stream index that consumeriwill read next. -
Lazy pulling: When a consumer needs an item at position
p, we check ifp - base < len(buffer). If not, we're the leading consumer, so we pull from the source until we reach that position or exhaust the stream. -
Eager pruning: After each advance, we compute the minimum position across all consumers. Any buffered items before that position have been read by everyone, so we pop them from the front of the deque and increment
baseaccordingly.
Why it works:
- Every consumer reads items in order from their current position
- The buffer contains exactly the items between the slowest and fastest consumer
- Items are pulled from the source only when the leading consumer needs them
- Items are freed as soon as the slowest consumer advances past them
Handling operations:
"next": advance the specified consumer by one position, return the value orNoneif exhausted"list": repeatedly advance the consumer until exhausted, collecting all values into a list
Complexity
Time: O(m · (n + v)) where m is the number of operations, n is the number of consumers, and v is the stream length. Each advance operation computes min(positions) in O(n) and may pull from the source. Across all operations, we pull each of the v items exactly once, giving O(v) total for pulling. Pruning processes each item once across all operations, contributing O(v). Computing minimums costs O(m · n).
Space: O(L + n) where L is the maximum lag (difference between fastest and slowest consumer positions). The buffer holds at most L items, and we store n positions.
Solution
from collections import deque
from typing import List, Optional
def multi_reader_stream(values: List[int], n: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[object]]:
source = iter(values)
buffer = deque()
base = 0
positions = [0] * max(0, n)
exhausted = False
results = []
def advance(index):
nonlocal base, exhausted
position = positions[index]
while position >= base + len(buffer) and not exhausted:
try:
buffer.append(next(source))
except StopIteration:
exhausted = True
if position >= base + len(buffer):
return None, False
value = buffer[position - base]
positions[index] += 1
if positions:
earliest = min(positions)
while base < earliest:
buffer.popleft()
base += 1
return value, True
for operation, args in zip(operations, arguments):
index = args[0]
if operation == "next":
value, found = advance(index)
results.append(value if found else None)
elif operation == "list":
items = []
while True:
value, found = advance(index)
if not found:
break
items.append(value)
results.append(items)
return results