← Questions

Iterator that yields one array first, then the rest of another

0
GoogleCodingLast asked Jan 2026

Design an iterator over two integer arrays, a and b, that returns elements in this order:

  1. Every element of b, in its original order (duplicates included).
  2. Then every element of a whose value does not appear anywhere in b, in a'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.

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding