Interleaving Iterators
MediumIterator · Coinbase
This models a common Coinbase iterator exercise. You are given a list of sources, each describing an iterator:
["list", values]: yields the integers invaluesin order, then is exhausted.["range", start, end, step]: yieldsstart,start + step,start + 2*step, ... for as long as the value is<= end, then is exhausted. (Ifstart > endit yields nothing.)["cycle", values]: yields the values in order and then starts over from the beginning, forever. A cycle over an empty list yields nothing and is exhausted immediately.
Build an interleaving iterator over the sources: repeatedly visit the sources in their original order, taking the next value from each source that still has one. Exhausted sources are skipped from then on.
Return the first limit values the interleaving iterator produces, or all of them if every source runs out before limit values are produced.
Ranges can be enormous and cycles never end, so values must be produced lazily rather than by expanding each source up front.
Example 1
- Input:
- sources = [["list", [1, 2, 3]], ["range", 10, 30, 10], ["cycle", [7, 8]]], limit = 10
- Output:
- [1, 10, 7, 2, 20, 8, 3, 30, 7, 8]
- Explanation
- Each round takes one value from every source in order: 1, 10, 7, then 2, 20, 8, then 3, 30, 7. The list and the range are then exhausted, so only the cycle keeps producing, and its next value 8 is the 10th.
Example 2
- Input:
- sources = [["range", -3, 3, 3], ["list", []], ["list", [5, 6, 7, 8]]], limit = 100
- Output:
- [-3, 5, 0, 6, 3, 7, 8]
- Explanation
- The empty list never produces anything. Once the range (-3, 0, 3) runs out, the remaining list values follow. Every source is exhausted after 7 values, before the limit is reached.
Example 3
- Input:
- sources = [["cycle", []], ["range", 1, 1000000000, 1]], limit = 4
- Output:
- [1, 2, 3, 4]
- Explanation
- An empty cycle produces nothing. The range is huge, so it must be generated lazily; only its first 4 values are needed.
Constraints
0 <= sources.length <= 10000 <= limit <= 10^5- List and cycle sources hold at most
10^4values each - For ranges:
-10^9 <= start, end <= 10^9and1 <= step <= 10^9