Zigzag Iterator - Problem
Imagine you have two lists of numbers, and you want to create an iterator that returns elements from both lists in a zigzag pattern - first from list 1, then from list 2, then back to list 1, and so on.
Your task is to implement a ZigzagIterator class with the following methods:
ZigzagIterator(v1, v2): Initialize with two integer vectorshasNext(): Returnstrueif there are more elements to iteratenext(): Returns the next element in zigzag order
Example: Given v1 = [1,2] and v2 = [3,4,5,6], the iterator should return elements in order: 1, 3, 2, 4, 5, 6
This is a classic design pattern problem that tests your understanding of iterators and state management!
Input & Output
example_1.py โ Basic Zigzag
$
Input:
v1 = [1,2], v2 = [3,4,5,6]
โบ
Output:
[1, 3, 2, 4, 5, 6]
๐ก Note:
The iterator alternates between v1 and v2: first 1 from v1, then 3 from v2, then 2 from v1, then 4 from v2, and finally the remaining elements 5,6 from v2
example_2.py โ Empty Vector
$
Input:
v1 = [1], v2 = []
โบ
Output:
[1]
๐ก Note:
When one vector is empty, the iterator simply returns all elements from the non-empty vector
example_3.py โ Equal Length
$
Input:
v1 = [1,2,3], v2 = [4,5,6]
โบ
Output:
[1, 4, 2, 5, 3, 6]
๐ก Note:
With equal length vectors, the pattern is perfectly alternating until both vectors are exhausted
Visualization
Tap to expand
Understanding the Visualization
1
Setup
Dealer has two decks: Blue deck [1,2] and Orange deck [3,4,5,6]
2
Deal Pattern
Deal from Blue โ Orange โ Blue โ Orange, continuing until decks are empty
3
Queue Management
Use a queue to remember deck order, rotating decks as they're used
4
Completion
When a deck is empty, it's removed from rotation naturally
Key Takeaway
๐ฏ Key Insight: Use a queue to naturally rotate between vectors, eliminating the need for complex state tracking or pre-merging. The queue automatically handles the zigzag pattern and gracefully removes exhausted vectors.
Time & Space Complexity
Time Complexity
O(1)
O(1) for each next() and hasNext() operation, total O(n+m) for all elements
โ Linear Growth
Space Complexity
O(1)
Only storing pointers and queue with at most 2 elements, no extra space for merging
โ Linear Space
Constraints
- 0 โค v1.length, v2.length โค 1000
- 1 โค v1[i], v2[i] โค 1000
- At most 1000 calls will be made to next and hasNext
- Follow up: What if you are given k vectors? How would you extend your solution?
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code