You are given two lists of integers, v1 and v2. Implement an iterator that returns their elements alternately: the first element of v1, then the first element of v2, then the second element of v1, then the second element of v2, and so on. Once one list is exhausted, the iterator returns the remaining elements of the other list in their original order.
Write a function that returns the complete sequence of values the iterator produces, in order.
As a follow-up, consider how your approach extends when you are given k lists instead of two.
Function Signature
def zigzag_iterator(v1: list[int], v2: list[int]) -> list[int]:
...
Rules
-
While both lists still have elements, the order is one element from
v1
, then one from
v2
, starting with
v1
.
-
Elements from the same list keep their original relative order.
-
Either list may be empty. In that case the output is the other list unchanged.
-
The output contains every input element exactly once, so its length is
len(v1) + len(v2)
.
Constraints
-
0 <= len(v1), len(v2) <= 1000
-
1 <= len(v1) + len(v2) <= 2000
-
-2^31 <= v1[i], v2[i] <= 2^31 - 1
Examples
Input: v1 = [1, 2], v2 = [3, 4, 5, 6]
Output: [1, 3, 2, 4, 5, 6]
Taking one element at a time gives 1 (from v1), 3 (from v2), 2 (from v1), 4 (from v2). Now v1 is used up, so the remaining elements of v2, 5 and 6, follow in order.
Input: v1 = [1, 2, 3], v2 = [4, 5, 6]
Output: [1, 4, 2, 5, 3, 6]
Both lists have the same length, so the output alternates all the way through and ends with the last element of v2.
Input: v1 = [10, 20, 30], v2 = [-5]
Output: [10, -5, 20, 30]
v2 runs out after its only element, so the remaining elements of v1, 20 and 30, are returned in their original order.