NeetCode #33LC-281MediumArrays & HashingNC Algo100
← Back to All Problems#33 · #281 · Zigzag Iterator(锯齿迭代器)
📌 Problem Statement & Constraints
Given two vectors
v1 and v2, implement an iterator that returns their elements in alternating order, starting with v1. If one vector is exhausted, continue with the other. Implement next() and hasNext(). Constraints: 0 <= v1.length, v2.length <= 1000.💡 Core Algorithmic Approaches
- Keep the two vectors in an array along with a per-vector read position, plus an index of which vector is next in the rotation.
next()advances the rotation index and returns the next element from whichever vector is not exhausted, skipping any that are.- The
while Trueloop is safe becausenext()is only called whenhasNext()is true, so at least one vector still has elements. hasNext()is ananyover the read positions. The design generalises tokvectors simply by growing the array.
💻 Benchmark Python3 Implementation
class ZigzagIterator:
def __init__(self, v1: List[int], v2: List[int]):
self.vs = [v1, v2] # easily extended to k vectors
self.pos = [0, 0]
self.turn = 0
def next(self) -> int:
while True:
i = self.turn
self.turn = (self.turn + 1) % len(self.vs) # round-robin
if self.pos[i] < len(self.vs[i]):
v = self.vs[i][self.pos[i]]
self.pos[i] += 1
return v
def hasNext(self) -> bool:
return any(self.pos[i] < len(self.vs[i]) for i in range(len(self.vs)))⚡ Complexity Deep Dive
⏱️ Time Complexity
O(1) amortised per next() call: the loop skips at most one exhausted vector per step, and hasNext is O(k) with k = 2.
💾 Space Complexity
O(k) for the position array; the input vectors are not copied.
⚠️ Interview Pitfalls & Follow-ups
- Assuming both vectors have equal length: they need not, so the alternating logic must handle exhaustion.
- Advancing the turn index only when an element is returned: it must advance every iteration of the skip loop, otherwise an exhausted vector blocks progress.
- Using a single global index into a flattened array: this destroys the alternating order, which is the entire point.
- Raising when
next()is called on an exhausted iterator: the contract guaranteeshasNext()is checked first, but a defensive guard is fine.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
锯齿迭代器
给出两个整数数组 v1 和 v2,请实现一个迭代器,交替返回两个数组中的元素。实现 ZigzagIterator 类: __init__(v1, v2) 初始化; next() 返回下一个元素; hasNext() 判断是否还有元素。当一个数组耗尽时,应连续返回另一个数组的剩余元素。进阶:如果给你 k 个一维数组,如何扩展你的设计?约束:0 ≤ v1.length, v2.length ≤ 1000;最多调用 10^4 次 next / hasNext。
核心要点
- 轮转指针(标准解) :维护一个「当前应访问哪个数组」的下标 i ,以及每个数组各自的读指针 ptr[k] 。
- next 的逻辑 :若当前数组已耗尽,就循环切换到下一个未耗尽的数组;取出元素后把读指针后移,并让 i 轮转到下一个数组。
- hasNext 的逻辑 :只要存在任一数组的读指针未到末尾,就返回 True。
- 为什么用「轮转」而非「拼接」 :拼接成一个大数组再顺序返回是 O(n) 预处理,且丧失了「交替」语义的直观性;轮转指针天然支持 k 个数组的扩展。
- k 个数组的扩展(进阶答案) :把两个数组换成长度为 k 的数组列表, i = (i + 1) % k 即可,代码结构完全不变。
常见陷阱
- 用两个独立的布尔标志代替统一下标 :可以工作但难以扩展到 k 个数组,且边界分支会急剧膨胀。轮转下标是更优雅的写法。
- next 时忘记轮转 self.i :会导致连续两次从同一数组取元素,失去「交替」语义。
- hasNext 只看当前数组 :必须检查 所有 数组是否都已耗尽,只看当前数组会提前返回 False。
- while 循环可能死循环 :若所有数组都耗尽, while 会无限轮转。调用方必须先确认 hasNext() 为真再调用 next() ——面试中应主动说明这个前置约定。
参考实现
class ZigzagIterator:
def __init__(self, v1: list[int], v2: list[int]):
self.vs = [v1, v2]
self.ptr = [0, 0] # 每个数组的读指针
self.i = 0 # 当前轮到的数组下标
def next(self) -> int:
# 跳过已耗尽的数组
while self.ptr[self.i] >= len(self.vs[self.i]):
self.i = (self.i + 1) % len(self.vs)
v = self.vs[self.i][self.ptr[self.i]]
self.ptr[self.i] += 1
self.i = (self.i + 1) % len(self.vs) # 轮转到下一个数组
return v
def hasNext(self) -> bool:
return any(self.ptr[k] < len(self.vs[k]) for k in range(len(self.vs)))