KatInterview

Multi-Consumer Iterator with Shared Buffering

Data Structure DesignAuto-graded · 19 test cases
HardAuto-gradedData Structure Designiteratorsgeneratorsmemory-management

Last 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 stream
  • n: the number of independent consumers (iterators) to create
  • operations: a list of operation names to perform
  • arguments: 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

  1. "next" with argument [index]: advance consumer index by one element and return that element. If the consumer has exhausted the stream, return None.

  2. "list" with argument [index]: consume all remaining elements from consumer index and 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 n consumers 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 ≤ 100
  • 0 ≤ len(values) ≤ 10,000
  • 1 ≤ len(operations) ≤ 1,000
  • len(operations) == len(arguments)
  • Each operation references a valid consumer index: 0 ≤ index < n
  • All elements in values are 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