Lazy K-Way Union Iterator
Learn this problemProblem statement
You are given sortedIterators, where each row represents the values produced by one finite iterator in nondecreasing order, and an ordered list of iterator operations.
Process the operations using one lazy union iterator over all input iterators:
has_nextreturns whether at least one input iterator still has an unconsumed value. It must not consume any value.nextreturns the smallest currently available value as a base-10 string and advances only the input iterator that supplied that value.- If several iterators currently expose the same minimum value, use the iterator with the smallest input index. Equal values are separate elements and must all be returned.
- If
nextis called after every input iterator is exhausted, returnERROR_EXHAUSTEDwithout changing state.
Return one string result for every operation, in order. A has_next result is true or false.
The iterator must be lazy: do not materialize the complete merged sequence. Keep only the state needed to identify the next available value and advance its source iterator.
Function
runUnionIterator(sortedIterators: int[][], operations: String[]) → String[]Examples
Example 1
sortedIterators = [[1,4,7],[2,3,8]]operations = ["has_next","next","next","has_next","next"]return = ["true","1","2","true","3"]The first query observes that values remain. The next three consumed values are 1, 2, and 3; each comes from the iterator whose current value is globally smallest.
Example 2
sortedIterators = [[1,1,9],[1,2],[]]operations = ["next","next","next","next","next","next","has_next","next"]return = ["1","1","1","2","9","ERROR_EXHAUSTED","false","ERROR_EXHAUSTED"]All three copies of 1 are retained. After 9 is consumed, repeated exhausted calls do not change state, and has_next remains false.
Constraints
0 <= sortedIterators.length <= 200000.- The total number of values across all rows is at most
200000. - Each row is sorted in nondecreasing order.
- Every value fits in a signed 32-bit integer.
0 <= operations.length <= 200000.- Every operation is either
has_nextornext. - The solution must not materialize the complete merged sequence.