Replay Operations on a Skip-Ahead Iterator
Data Structure DesignAuto-graded · 16 test casesLast updated
Simulate a forward-only iterator that yields every k-th element, with an idempotent has-next check, and return the results of a scripted sequence of operations.
Skip-Ahead Iterator Replay
You are modeling an iterator that reads a source sequence in a single forward pass and exposes only every step-th element. Instead of building a class, you write one function that replays a scripted list of operations against such an iterator and reports what each operation produced.
Behavior of the iterator
The iterator is created over values with a positive integer step. It can only move forward through the source. It must not index into the source or use its length.
- The elements it exposes are those at positions
0, step, 2*step, 3*step, ...of the source, in that order. Positions that do not exist are never exposed. hasNextreports whether at least one more exposed element is available. It returnsTrueorFalse. Calling it repeatedly without an interveningnextmust give the same answer every time and must not change which element is exposed next.nextreturns the next exposed element and moves past it. If no exposed element remains, it returnsNoneinstead (this stands in for raising an end-of-iteration error).
The first next returns the element at position 0. Each later next returns the element step positions after the previous one. If fewer than step elements remain after the last exposed one, the iterator is finished.
Task
Given values, step, a list operations, and a list arguments, process the operations in order, each as described above. Each entry of operations is either "hasNext" or "next". The entry at the same index in arguments is an empty list for every operation and can be ignored.
Return a list with one result per operation, in order:
- For
"hasNext", appendTrueorFalse. - For
"next", append the returned element, orNoneif nothing is left.
Constraints
1 <= step <= 10^90 <= len(values) <= 10^6len(operations) == len(arguments)- Every operation is either
"hasNext"or"next". - Process the source in one forward pass, keeping only O(1) extra memory beyond the result list (at most one buffered element).
- A very large
stepon a short list must not cause a loop ofstepiterations: stop as soon as the source runs out.
Examples
Example 1
Input: replay_skip_iterator([10, 20, 30, 40, 50, 60, 70], 2, ['hasNext', 'next', 'hasNext', 'next', 'next', 'next', 'hasNext', 'next'], [[], [], [], [], [], [], [], []])
Output: [True, 10, True, 30, 50, 70, False, None]
Example 2
Input: replay_skip_iterator([1, 2, 3, 4, 5], 3, ['next', 'next', 'hasNext', 'next'], [[], [], [], []])
Output: [1, 4, False, None]
Hints
Hint 1
A forward-only source cannot tell you whether another element exists unless you actually read it, so keep a single lookahead slot.
Hint 2
After capturing the element at a target position, discard the next step - 1 elements so the source sits at the following target position. If the source ends during the discarding, the captured element is still valid.
Hint 3
Use a separate boolean to mark whether the lookahead slot is filled, plus a flag for source exhaustion, so hasNext stays idempotent and repeated calls never read further.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The source can only be read forward, so the only way to answer hasNext is to actually read the next target element and hold it. We keep one lookahead slot and two flags:
held: the element to be returned next.has_held: whetherheldcontains a valid, not-yet-returned element.finished: whether the source has run out, so we stop touching it.
A helper load() does all the work:
- If an element is already held or the source is finished, return immediately. This makes
hasNextidempotent. - Otherwise read one element into
held. This is the element at position0,step,2*step, and so on. If the source is empty at this point, markfinished. - Discard the next
step - 1elements so the source is positioned at the next target. If the source ends during this skipping, just stop; the element already captured is still valid.
hasNext calls load() and reports has_held. next calls load(); if nothing is held it appends None, otherwise it appends the held value and clears the slot.
Why it is correct
Invariant: whenever nothing is held and the source is not finished, the source is positioned at some multiple of step, which is exactly the next position to expose.
- Initially the source is at position
0. load()reads positionj*stepand skipsstep - 1elements, leaving the source at(j+1)*step.nextonly clears the slot and does not touch the source.
So the exposed elements are exactly those at positions 0, step, 2*step, .... Repeated hasNext calls return early once an element is held or the source is finished, so they change nothing. Because skipping stops at the end of the source, a huge step on a short list does not loop step times. A short tail (fewer than step elements after the last exposed one) is consumed cleanly, and the captured element is still returned.
A separate has_held flag is used instead of checking held is None, so the logic does not depend on the values themselves.
Complexity
- Time: each
load()touches the source at moststeptimes, and never more than the number of remaining elements. Across the whole run the source is read at most once per element, so the total is O(n + number of operations). - Space: O(1) auxiliary (one held value and two booleans), apart from the output list.
Reference solution
from typing import List
def replay_skip_iterator(values: List[int], step: int, operations: List[str], arguments: List[List]) -> List[object]:
source = iter(values)
held = None
has_held = False
finished = False
def load():
nonlocal held, has_held, finished
if has_held or finished:
return
try:
held = next(source)
except StopIteration:
finished = True
return
for _ in range(step - 1):
try:
next(source)
except StopIteration:
break
has_held = True
out = []
for op, _ in zip(operations, arguments):
if op == "hasNext":
load()
out.append(has_held)
elif op == "next":
load()
if not has_held:
out.append(None)
else:
out.append(held)
held = None
has_held = False
else:
raise ValueError("unknown operation")
return out