Here is the full interview question "Coding - Interleave Iterator" asked at Snowflake:
Problem Statement: Given two lists of integers, create an iterator that returns a sequence of alternating elements from each list. The iterator should continue to alternate between the two lists until one of them is exhausted. Once a list is exhausted, the iterator should return all remaining elements from the other list.
Examples:
list1 = [1, 2, 3] and list2 = [4, 5, 6, 7], the iterator should return [1, 4, 2, 5, 3, 6, 7].list1 = [1, 2] and list2 = [3, 4, 5, 6], the iterator should return [1, 3, 2, 4, 5, 6].Constraints:
Hints:
Solution: `python class InterleaveIterator: def init(self, list1, list2): self.list1 = list1 self.list2 = list2 self.index1 = 0 self.index2 = 0
def hasNext(self):
return self.index1 < len(self.list1) or self.index2 < len(self.list2)
def next(self):
if self.index1 < len(self.list1):
result = self.list1[self.index1]
self.index1 += 1
else:
result = self.list2[self.index2]
self.index2 += 1
return result
`
This solution uses two pointers to keep track of the current position in each list. The hasNext method checks if there are any remaining elements in either list, and the next method returns the next element by alternating between the two lists. Once a list is exhausted, the iterator returns all remaining elements from the other list.