Simulate a Forward-Only Row Cursor
Data Structure DesignAuto-graded · 22 test casesLast updated
Simulate a forward-only cursor over a list of rows, where a peek call is side-effect free and an advance call returns the next row or None at the end.
You are given a list of rows (each row is a dictionary) and a sequence of commands to run against a forward-only cursor over those rows. Your job is to simulate the cursor and report what each command returns.
Cursor behavior
The cursor starts positioned before the first row and moves only forward. It supports two commands:
"has_next": reports whether at least one unread row remains. It returnsTrueif so andFalseotherwise. This command only peeks: calling it any number of times in a row never changes the cursor's position."next": if an unread row remains, it returns that row (the exact dictionary from the input) and moves the cursor forward by exactly one row. If no unread row remains, it returnsNoneand the cursor stays where it is.
Rows are returned in their original order, and each row is returned at most once.
Task
Process the commands in order and return a list containing one result per command, in the same order as the commands. Each entry is a boolean for has_next, and either a row dictionary or None for next.
Constraints
0 <= len(rows) <= 10^50 <= len(operations) <= 10^5- Each element of
operationsis exactly"has_next"or"next". - Rows are dictionaries with arbitrary keys and values; do not modify them.
- Calling
nextafter the rows are exhausted must not raise an error and must not change the cursor state.
Examples
Example 1
Input: simulate_cursor([{'id': 1}, {'id': 2}, {'id': 3}], ['has_next', 'next', 'has_next', 'next', 'has_next', 'next', 'has_next'])
Output: [True, {'id': 1}, True, {'id': 2}, True, {'id': 3}, False]
Example 2
Input: simulate_cursor([], ['has_next', 'next', 'has_next'])
Output: [False, None, False]
Example 3
Input: simulate_cursor([{'id': 7}], ['has_next', 'has_next', 'next', 'has_next', 'next'])
Output: [True, True, {'id': 7}, False, None]
Example 4
Input: simulate_cursor([{'id': 1}, {'id': 2}], ['next', 'next', 'next', 'has_next', 'next'])
Output: [{'id': 1}, {'id': 2}, None, False, None]
Hints
Hint 1
Keep a single integer position that records how many rows have been consumed so far.
Hint 2
has_next should only compare the position to the number of rows; it must not change the position.
Hint 3
next should check for exhaustion first: return None without moving if nothing is left, otherwise return the row at the position and then increase the position by one.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Track one integer, position, the index of the next unread row. Then handle each command:
has_next: appendposition < len(rows). Nothing changes, so the call is idempotent.next: ifposition >= len(rows), appendNoneand leavepositionalone. Otherwise appendrows[position]and incrementpositionby one.
Why it is correct
The cursor contract has three parts: peeking has no side effects, advancing moves exactly one row, and reading past the end is harmless. The design satisfies each directly. Only next modifies position, and only when a row is actually returned. Because has_next never touches the state, repeated calls give the same answer. Because position increases by exactly one per returned row, every row is produced once and in order. Guarding the end case keeps the position from drifting beyond len(rows), so later has_next calls stay False.
A common mistake is to advance the position inside has_next. That makes one loop iteration move the cursor twice and skips rows.
Complexity
- Time: O(m), where m is the number of operations. Each one takes constant time.
- Space: O(m) for the output list, with only O(1) extra state beyond that.
Reference solution
from typing import List, Dict
def simulate_cursor(rows: List[Dict[str, object]], operations: List[str]) -> List[object]:
position = 0
n = len(rows)
results = []
for op in operations:
if op == "has_next":
results.append(position < n)
elif op == "next":
if position >= n:
results.append(None)
else:
results.append(rows[position])
position += 1
return results