Multi-Stream Round-Robin Iterator
AirbnbOnsiteMedium
You are merging several streams of characters into one. Each stream yields single characters and then runs out; the constructor of MultiStreamIterator receives the streams' contents as a list of strings, and the starter already turns each one into an iterator. A stream can be empty. The starter also provides the abstract class StreamIterator with has_next() and next(), and MultiStreamIterator must implement that interface.
The merged sequence is round robin: take one element from the first stream, then one from the second, and so on to the last, then start again from the first. A stream that has run out is skipped from then on, and the sequence ends when every stream has. For streams abc, de and f it is a d f b e c.
Part 1: Round-robin iterator
Implement:
has_next()returns whether the merged sequence has another element. It can be called any number of times, in any order withnext(), and it must never consume an element: the calls tonext()return the same characters whether or nothas_next()was called in between.next()returns the next element of the merged sequence and raisesStopIterationwhen there is none.
Each next() should cost constant time amortized, however many streams there are and however many of them have already run out.
- Example 1
- init
[["abc","de","f"]]- operations
[["next",[]],["next",[]],["next",[]],["next",[]],["next",[]],["next",[]],["has_next",[]]]- Output
["a","d","f","b","e","c",false]
Why: The first round takes a from abc, d from de and f from f. In the second round f is exhausted and skipped, so b and e follow. In the third only abc is left, so c comes last. After it has_next() is false.
Constraints
0 <= len(streams) <= 10^5- The total number of characters over all streams is at most
10^6 1 <= len(operations) <= 10^6