KatInterview

Simulate a Forward-Only Row Cursor

Data Structure DesignAuto-graded · 22 test cases
EasyAuto-gradedData Structure Designsimulationiteratorcursor

Last 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 returns True if so and False otherwise. 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 returns None and 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^5
  • 0 <= len(operations) <= 10^5
  • Each element of operations is exactly "has_next" or "next".
  • Rows are dictionaries with arbitrary keys and values; do not modify them.
  • Calling next after 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.