Problem · Array

Resumable List Iterator

Learn this problem
MediumOpenAIFULLTIMEPHONE SCREEN

Problem statement

Design a finite iterator over an integer array whose progress can be saved and restored.

Iterator Behavior

  • Return the next value and signal exhaustion after the final value.
  • getState() returns a serializable, opaque state representing the current position.
  • setState(state) restores the iterator so that subsequent values are exactly the values that remained when the state was saved.

A caller must not assume that a state is an array index. A saved state must continue to work after the original iterator has advanced or become exhausted.

State Restoration

Save the iterator state before reading the first value and after every returned value, including the exhausted position. Restore a fresh iterator from each saved state, read it to exhaustion, and return all resulting suffixes in save order.

Row i of the returned int[][] contains all values returned after restoring the state saved after exactly i values had been consumed. The final row is empty because it represents the exhausted state.

What the interview report shared

The recent phone screen asked candidates to write detailed tests before implementing a resumable iterator, beginning with a list and following with a file iterator. A direct earlier report supplied an abstract interface with iteration, get_state, and set_state, and required testing restoration from every position without assuming how state was represented.

Function

resumeSuffixes(values: int[]) → int[][]

Examples

Example 1

values = [4, 7, 9]return = [[4, 7, 9], [7, 9], [9], []]

The saved states represent the positions before 4, before 7, before 9, and after the iterator is exhausted. Restoring each state produces the corresponding suffix.

More OpenAI problems

drafts saved locally
public int[][] resumeSuffixes(int[] values) {
  // write your code here
}
values[4, 7, 9]
expected[[4, 7, 9], [7, 9], [9], []]
checking account