← Questions
Lazy tee: split one iterator into n independent iterators
0
I was asked this
No reports yet. Sign in to say where you were asked it.
Implement tee in Python: from one source iterator, create n independent iterators that each yield the full sequence. It must be lazy: pull from the source only when some copy needs an item it has not seen, read each source item exactly once, and keep in memory only the items that some copy has not read yet.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
tee(iterable, n: int = 2) -> tuple[Iterator, ...]—niterators over the same items. When the source is exhausted, every copy stops after yielding everything before that point. Using the original source directly afterwards is not supported.
Example
a, b = tee(iter([1, 2, 3]), 2)
next(a) -> 1 # pulls 1 from the source
next(a) -> 2 # pulls 2; the buffer holds 1 and 2 for b
next(b) -> 1 # from the buffer, no new pull
list(a) -> [3] # pulls 3
list(b) -> [2, 3]
Constraints
- The source may be infinite or expensive, so no eager reads.
- Copies may be read at very different speeds; memory should be bounded by the gap between the fastest and slowest copy.
Clarifying questions
- Must each source item be read exactly once?
- What happens if one copy is never read: is unbounded buffering acceptable?
- Should exceptions raised by the source reach every copy?
- Does it need to be thread-safe?
What a strong answer covers
- A shared buffer (a deque) with each copy holding its own position, or a linked list of nodes that copies walk, so items no copy still needs are freed automatically by garbage collection.
- Pulling from the source only when the fastest copy reaches the end of the buffer, and propagating
StopIterationto every copy. - Memory equal to the spread between copies; when one copy lags far behind, buffering cannot be avoided, and saying so.
- Generators versus classes with
__iter__and__next__, and tests with a source that counts its reads.
Follow-ups
- Make it thread-safe.
- Let a copy be closed early so its position no longer pins the buffer.
- The source raises an exception halfway. What should each copy see?
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
