KatInterview

Simulate Alternating Tic-Tac-Toe Game Engine

Data Structure DesignAuto-graded · 16 test cases
HardAuto-gradedData Structure Designdesign-dsarraysstate-machine

Last updated

Process a series of game instructions to maintain state, validate turns and positions, and return outcome status for each operation.

Design a state machine engine for a classic 3x3 Tic-Tac-Toe game. You are given a sequence of operation names and their corresponding arguments.

The board starts empty. The game rules are defined as follows:

  • Player 'X' and Player 'O' take turns placing their marks.
  • Player 'X' must always make the first valid move.
  • The board consists of a 3x3 grid with row indices 0..2 and column indices 0..2.

Each element in operations is paired with the element at the same index in arguments:

  • For an operation name equal to "move", the argument is a list [row, col, player].

For each operation in the input sequence, process the command and append one of the following strings to the output list:

  • "Invalid": The command is not recognized (i.e. operation is not "move"), the game has already concluded, the coordinates are out of bounds (less than 0 or greater than 2), the specified cell is already occupied, the player symbol is invalid (not 'X' or 'O'), or it is not that player's turn. Invalid operations must not alter the game state or change whose turn it is.
  • "Win": The move is valid and completes a 3-in-a-row alignment (horizontally, vertically, or diagonally) for the player. The game concludes immediately after a win.
  • "Draw": The move is valid, does not form a 3-in-a-row alignment, but fills the 9th cell of the grid. The game concludes immediately after a draw.
  • "Success": The move is valid, the game has not ended, and turn transfers to the other player.

Constraints

  • operations and arguments are parallel lists of equal length N (1 <= N <= 100).
  • Each element of operations is a string.
  • Each element of arguments is a 3-element list [row, col, player]. row and col are integers; player is a string.

Examples

Example 1

Input: tic_tac_toe(['move', 'move', 'move', 'move', 'move'], [[0, 0, 'X'], [0, 1, 'O'], [1, 1, 'X'], [0, 2, 'O'], [2, 2, 'X']])

Output: ['Success', 'Success', 'Success', 'Success', 'Win']

Example 2

Input: tic_tac_toe(['move', 'move', 'move', 'move', 'move', 'move'], [[0, 0, 'X'], [0, 1, 'O'], [1, 1, 'X'], [0, 2, 'O'], [2, 2, 'X'], [2, 0, 'O']])

Output: ['Success', 'Success', 'Success', 'Success', 'Win', 'Invalid']

Hints

Hint 1

Validate turn order, boundary limits, and cell occupancy prior to modifying the board state.

Hint 2

If an operation is invalid, do not toggle the active player turn or alter the board state.

Hint 3

Evaluate win conditions immediately upon placing a valid mark; check draw conditions only if no win occurred on the 9th move.