Coinbase OA Interview Question: Interleaving Streams and Iterator Design

26 Views
No Comments

Interleaving Streams

We are building a page that pulls posts from multiple different sources and displays them in a unified feed. You are going to build a function named interleave that orders these posts so each source gets a share of screen time.

Create a function interleave that takes a list of lists of integers and returns a single list of integers back. The response should take the first element from each list and add it to the resulting list before moving on to the second one, and so on. As lists are exhausted, they should be skipped over.

E.g. given the input: [[1,2,3],[4,5],[6],[],[7,8,9]]

You should return: [1,4,6,7,2,5,8,3,9]

Infinite Streams as an Alternative

We now want to start consuming data from sources that never run out of content (like Facebook and Twitter). Our existing implementation would never complete because we couldn’t hold the lists in memory. We are going to try and change our approach a bit.

Build an iterator interface that supports the following functions:

  • int getNext() returns the next value in the iterator and shifts it forward.
  • bool hasNext() lets you know if there is a value left in the iterator. If hasNext() returns true, getNext() must return a value. Additionally, hasNext() must be idempotent and multiple calls return the same result.

Implement this interface with two iterators:

  • One that takes a list and turns it into an iterator.
  • One that iterates through a range of integers, taking a start integer, a finish integer, and a step integer.
  • [execution time limit] 4 seconds (py3)
  • [memory limit] 2g

This Coinbase interview problem asks you to first interleave multiple integer lists in round-robin order, then extend the idea to an iterator abstraction for unbounded streams. The key skills are iterator design, state management, and lazy consumption of data sources, including a list-backed iterator and a numeric range iterator with a stable, idempotent hasNext().

END
 0