← 返回 openai 的题目列表Resumable Iterator for List and File
类型:online_judge
Problem: Design a Resumable Iterator
Design and implement a resumable iterator. In addition to normal iteration, it must be able to save its current state and later resume from that state.
The interview usually expects you to:
Design detailed test cases first;
Then implement the iterator;
Cover state saving, state restoration, and boundary cases.
Part 1: List Iterator
Implement ListResumableIterator for a list of strings.
It should support:
has_next() -> bool: returns whether there is another element;
next() -> str: returns the next element, or raises StopIteration if exhausted;
get_state() -> dict: returns a serializable state;
set_state(state: dict) -> None: restores the iterator to a previous state.
Assumptions:
The list does not change between saving and restoring state;
The state should contain only the minimum information required to resume.
Part 2: File Iterator Follow-up
Extend the design to a file iterator FileLineResumableIterator.
The file iterator iterates line by line and supports the same operations:
has_next() -> bool
next() -> str
get_state() -> dict
set_state(state: dict) -> None
Assumptions:
The file content does not change between saving and restoring state;
Each call to next() returns one line without the trailing newline character;
After restoring, the iterator should continue from the exact saved position.
Constraints
List length: 0 <= n <= 10^5;
String length: 0 <= len(s) <= 10^3;
File size: up to 10^8 bytes;
Number of operations: up to 10^5.
Example Test Scenarios
Example 1: Save and restore a list iterator
items = ["a", "b", "c"]
next() -> "a"
save state
next() -> "b"
restore state
next() -> "b"
next() -> "c"
has_next() -> false
Example 2: Empty list
items = []
has_next() -> false
next() -> StopIteration
Example 3: Save and restore a file iterator
File content:
line1
line2
line3
Operations:
next() -> "line1"
save state
next() -> "line2"
restore state
next() -> "line2"
next() -> "line3"
has_next() -> false
Example
Input
LIST
3
a b c
8
HAS
NEXT
SAVE s1
NEXT
LOAD s1
NEXT
NEXT
HAS
Output
true
a
saved:s1
b
loaded:s1
b
c
false