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. IfhasNext()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
这道 Coinbase 面试题分成两部分:第一部分要求把多个列表按轮询方式交错合并,依次取每个列表的第一个元素、第二个元素,直到所有列表都遍历完;第二部分进一步把“列表”抽象成迭代器接口,要求实现 <code>getNext()</code> 和 <code>hasNext()</code>,并保证 <code>hasNext()</code> 可重复调用且结果稳定。题目核心是迭代器设计、惰性读取和对多个数据源的统一消费,适合用队列、指针或封装迭代器状态来实现。