Iterator that yields one array first, then the rest of another
I was asked this
No reports yet. Sign in to say where you were asked it.
Design an iterator over two integer arrays, a and b, that returns elements in this order:
- Every element of
b, in its original order (duplicates included). - Then every element of
awhose value does not appear anywhere inb, ina's original order.
Implement a class with this API:
class SubarrayFirstIterator:
def __init__(self, a: list[int], b: list[int]) -> None: ...
def has_next(self) -> bool: ...
def next(self) -> int: ...
-
has_next()returns whether another element remains. Calling it repeatedly must not change the result or skip elements. -
next()returns the next element, or raises an error when the iterator is exhausted. - The iterator should be lazy: do not build the full output list up front.
Constraints: 0 <= len(a), len(b) <= 10^5. Values are arbitrary integers. b may contain values that are not in a.
Example 1
a = [4, 1, 7, 3, 9], b = [7, 4]
output: 7, 4, 1, 3, 9
Example 2
a = [5, 2, 5, 8], b = [5]
output: 5, 2, 8
Both copies of 5 in a are skipped because 5 appears in b.
Reconstructed from the reported question; details may differ from what interviewers ask.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to submit your code; every attempt is kept here.
