MongoDB: Union iterator over two sorted iterators
Problem. Write a class that takes two iterators, each yielding strictly increasing values, and itself exposes hasNext() and next(). It must produce the union of both inputs in strictly increasing order. A value present in both appears once. Values may be ints or strings.
Constraints given. Inputs can be very large, so you cannot copy them into memory.
Examples. [2, 4, 6, 8, 10] and [1, 2, 3, 5, 8, 13] give 1, 2, 3, 4, 5, 6, 8, 10, 13. [apple, banana, orange, tree] and [apple, tree, zoo] give apple, banana, orange, tree, zoo. [1, 2, 3] with an empty iterator gives 1, 2, 3. Negative numbers should work too.
Approach. Keep one buffered head value from each input. On next(), return the smaller head and advance only that input; if both heads are equal, return it once and advance both. This uses constant extra space. The candidate said the trap was treating it like a linked list merge rather than handling the peek-ahead buffering.
Comments 0
No comments yet. Ask the author something, or add what happened in your own round.