Google questions

Independent Iterators

GoogleMedium

You are building tee, which splits one stream of values into several independent streams. Tee(source, n) wraps source, a list of integers that you must treat as a one-shot stream: read it at most once, from the start, and read a value only when some iterator needs a value that has not been read yet.

There are n iterators, numbered 0 to n - 1. Each one returns the values of source in order, from the first, and moves forward only when it is asked. The iterators do not affect each other.

Part 1: Tee

Implement:

  • next(i) returns the next value for iterator i, or null once iterator i has returned every value of source. Calling it again after that keeps returning null.
  • buffered() returns how many values have been read from source but not yet returned by every iterator. That is the number of values read from the source minus the number of values returned by the iterator that has returned the fewest. It is 0 before the first call.
  1. Example 1
    init
    [[1,2,3,4],2]
    operations
    [["buffered",[]],["next",[0]],["next",[0]],["buffered",[]],["next",[1]],["buffered",[]],["next",[1]],["buffered",[]],["next",[0]],["next",[0]],["next",[0]],["buffered",[]],["next",[1]],["next",[1]],["next",[1]],["buffered",[]]]
    Output
    [0,1,2,2,1,1,2,0,3,4,null,2,3,4,null,0]

    Why: Nothing is read at first, so buffered() is 0. Iterator 0 reads 1 and 2, so 2 values are held until iterator 1 catches up. After iterator 1 reads 1 the gap is 1, and after it reads 2 the gap is 0.

Constraints

  • 0 <= len(source) <= 10^5
  • -10^9 <= source[i] <= 10^9
  • 1 <= n <= 50
  • 0 <= i < n
  • 1 <= number of operations <= 10^5
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Independent Iterators: Google interview question | LoopCoach