[
design
]
BinarySearch 0728 Zipped Iterator
Problem statement
https://binarysearch.com/problems/Zipped-Iterator/
Solution
Equal to Leetcode 0281. Zigzag Iterator.
Complexity
Time is O(1)
and space for all operations is O(l1 + l2)
.
Code
class ZippedIterator:
def __init__(self, v1, v2):
self.v = [v1, v2]
self.p, self.turn = [0, 0], 0
def next(self):
if self.p[self.turn] < len(self.v[self.turn]):
ans = self.v[self.turn][self.p[self.turn]]
self.p[self.turn] += 1
self.turn = (self.turn + 1)%2
else:
self.turn = (self.turn + 1)%2
ans = self.v[self.turn][self.p[self.turn]]
self.p[self.turn] += 1
return ans
def hasnext(self):
return self.p[0] < len(self.v[0]) or self.p[1] < len(self.v[1])