KatInterview

Execute Turn-Based Movement Commands on a Line

Data Structure DesignAuto-graded · 18 test cases
EasyAuto-gradedData Structure Designsimulationstate-machinevalidation

Last updated

Tests state tracking and rule validation for alternating player moves on a bounded one-dimensional board.

You are building a controller for a two-player board game on a one-dimensional track with positions numbered 0 through n-1. Player 1 begins at position 0 and Player 2 begins at position n-1.

Players alternate turns, with Player 1 moving first. On each turn, the active player attempts to shift their piece by -1 (left), 0 (stay), or +1 (right).

A move succeeds if and only if all of the following hold:

  1. It is the correct player's turn.
  2. The destination position lies within [0, n-1].
  3. The destination position is not currently occupied by the other player.

When a move succeeds, the player's position updates and control passes to the opponent. When a move fails, the board state remains unchanged and the same player must try again.

Your task is to process a sequence of initialization and move commands, returning the outcome of each operation.

Input Format

You will receive two parallel lists:

  • operations: a list of command names, each either "GameSimulator" or "move".
  • arguments: a list of argument lists, one per command.

For "GameSimulator" commands, the argument list contains a single integer [n] specifying the board size. This command initializes (or reinitializes) the game.

For "move" commands, the argument list contains [player_id, direction], where player_id is 1 or 2 and direction is -1, 0, or +1.

Output Format

Return a list of results, one per command:

  • For "GameSimulator", append None (rendered as null in JSON).
  • For "move", append a two-element list [is_valid, game_over] where both are booleans.

is_valid is True if the move was accepted, False otherwise. game_over indicates whether the game has ended (note: under the occupancy rule, this will always be False because players cannot land on each other).

Constraints

  • 2 ≤ n ≤ 1000
  • 1 ≤ len(operations) ≤ 1000
  • player_id is always 1 or 2
  • direction is always -1, 0, or +1
  • The first operation is always "GameSimulator"

Examples

Example 1

Input: execute_board_commands(['GameSimulator', 'move', 'move'], [[5], [1, 1], [2, -1]])

Output: [None, [True, False], [True, False]]

Example 2

Input: execute_board_commands(['GameSimulator', 'move', 'move', 'move'], [[4], [1, 1], [1, 1], [2, -1]])

Output: [None, [True, False], [False, False], [True, False]]

Hints

Hint 1

Track three pieces of state: Player 1's position, Player 2's position, and whose turn it is next.

Hint 2

An invalid move must not change any state—positions and turn order stay exactly as they were.

Hint 3

Check all three validity conditions before updating anything. The opponent's position is at index 3 minus the current player's ID.