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.
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:
- 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.
Clarifying questions
- Should duplicates in
ball be returned (yes, per the rules), and duplicates inathat are not inbtoo? - Can the arrays change while iterating?
- Which error should
next()raise when exhausted:StopIteration? - Should the class also support Python's
forloop 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
bin order; phase 2 advances througha, skipping values in the set. -
has_nextmoves theaindex forward past skipped values and then only reads it, so calling it many times has no further effect;nextuses the same helper. -
O(1)amortized per call andO(len(b))extra space. - Tests both examples, empty
aorb,bwith values not ina, and repeatedhas_nextcalls.
Follow-ups
- Generalise to
karrays, each excluding the values of all earlier ones. - Remove the set's memory cost when
bis 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
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
