← Questions

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

0
GoogleCodingLast asked Jan 2026

A coding interview question asked in Google's first round (coding), last asked Jan 2026. It tests iterator, design and hash set.

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.

Clarifying questions

  • Should duplicates in b all be returned (yes, per the rules), and duplicates in a that are not in b too?
  • Can the arrays change while iterating?
  • Which error should next() raise when exhausted: StopIteration?
  • Should the class also support Python's for loop protocol?

What a strong answer covers

  • Builds a hash set of b's values at construction, O(len(b)), and keeps two indices instead of a merged list.
  • Phase 1 returns b in order; phase 2 advances through a, skipping values in the set.
  • has_next moves the a index forward past skipped values and then only reads it, so calling it many times has no further effect; next uses the same helper.
  • O(1) amortized per call and O(len(b)) extra space.
  • Tests both examples, empty a or b, b with values not in a, and repeated has_next calls.

Follow-ups

  • Generalise to k arrays, each excluding the values of all earlier ones.
  • Remove the set's memory cost when b is huge and sorted.
  • Support remove() of the last returned element.

Where it's asked

  • Google · First round: coding · Last asked Jan 202645 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI

What it tests

iterator · design · hash set

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