Leetcode #281: Zigzag Iterator
In this guide, we solve Leetcode #281 Zigzag Iterator in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Given two vectors of integers v1 and v2, implement an iterator to return their elements alternately. Implement the ZigzagIterator class: ZigzagIterator(List
v1, List v2) initializes the object with the two vectors v1 and v2.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Design, Queue, Array, Iterator
Intuition
We need level-order exploration or shortest-step expansion, which maps directly to a queue.
BFS guarantees the first time you reach a node is the shortest in unweighted graphs.
Approach
Initialize the queue with starting nodes and expand outward layer by layer.
Track visited nodes to avoid cycles and redundant work.
Steps:
- Initialize a queue with start nodes.
- Pop, process, and enqueue neighbors.
- Track visited nodes.
Example
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].
Python Solution
class ZigzagIterator:
def __init__(self, v1: List[int], v2: List[int]):
self.cur = 0
self.size = 2
self.indexes = [0] * self.size
self.vectors = [v1, v2]
def next(self) -> int:
vector = self.vectors[self.cur]
index = self.indexes[self.cur]
res = vector[index]
self.indexes[self.cur] = index + 1
self.cur = (self.cur + 1) % self.size
return res
def hasNext(self) -> bool:
start = self.cur
while self.indexes[self.cur] == len(self.vectors[self.cur]):
self.cur = (self.cur + 1) % self.size
if self.cur == start:
return False
return True
# Your ZigzagIterator object will be instantiated and called as such:
# i, v = ZigzagIterator(v1, v2), []
# while i.hasNext(): v.append(i.next())
Complexity
The time complexity is O(V+E). The space complexity is O(V).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.