Zigzag Iterator Problem
Description
LeetCode Problem 281.
Given two vectors of integers v1 and v2, implement an iterator to return their elements alternately.
Implement the ZigzagIterator class:
ZigzagIterator(List<int> v1, List<int> v2)initializes the object with the two vectorsv1andv2.boolean hasNext()returnstrueif the iterator still has elements, andfalseotherwise.int next()returns the current element of the iterator and moves the iterator to the next element.
Example 1:
Input: v1 = [1,2], v2 = [3,4,5,6]
Output: [1,3,2,4,5,6]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,3,2,4,5,6].
Example 2:
Input: v1 = [1], v2 = []
Output: [1]
Example 3:
Input: v1 = [], v2 = [1]
Output: [1]
Constraints:
0 <= v1.length, v2.length <= 10001 <= v1.length + v2.length <= 2000-2^31 <= v1[i], v2[i] <= 2^31 - 1
Follow up: What if you are given k vectors? How well can your code be extended to such cases?
Clarification for the follow-up question:
The "Zigzag" order is not clearly defined and is ambiguous for k > 2 cases. If "Zigzag" does not look right to you, replace "Zigzag" with "Cyclic".
Follow-up Example:
Input: v1 = [1,2,3], v2 = [4,5,6,7], v3 = [8,9]
Output: [1,4,8,2,5,9,3,6,7]
Solution
Approach: Queue of Vectors Taking Turns
Think of the vectors as standing in line, each waiting for its turn to hand out one element. A queue models this directly. Each entry is a vector plus the index of its next element:
- The constructor puts every non-empty vector into the queue,
v1first. next()takes the vector at the front, returns its current element, and, if it still has more, puts it at the back of the queue with the index moved by one. A vector that runs out simply leaves the line, so the remaining one keeps handing out elements on its own (like5, 6in Example 1).hasNext()is true while the queue is not empty.
Leaving empty vectors out at the start matters: otherwise next() would have to skip them, and hasNext() would be wrong for inputs like v1 = [].
This also answers the follow-up: with k vectors, put all k into the queue in order and nothing else changes. That gives the cyclic order 1, 4, 8, 2, 5, 9, 3, 6, 7 from the follow-up example.
Complexity: O(1) time for each next() and hasNext(). O(k) extra space for the queue, where k is the number of vectors (2 here).
import collections
class ZigzagIterator:
def __init__(self, v1: List[int], v2: List[int]):
# (vector, index of its next element) for each vector that still has elements, in turn order.
self.queue = collections.deque((v, 0) for v in (v1, v2) if v)
def next(self) -> int:
v, i = self.queue.popleft()
if i + 1 < len(v):
self.queue.append((v, i + 1)) # back of the line for its next turn
return v[i]
def hasNext(self) -> bool:
return len(self.queue) > 0