Simulate Alternating Tic-Tac-Toe Game Engine
Data Structure DesignAuto-graded · 16 test casesLast 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..2and column indices0..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
operationsandargumentsare parallel lists of equal lengthN(1 <= N <= 100).- Each element of
operationsis a string. - Each element of
argumentsis a 3-element list[row, col, player].rowandcolare integers;playeris 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.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Method Explanation
The problem asks us to build an in-memory game manager for Tic-Tac-Toe that tracks game status across a sequence of command instructions.
To model the game state, we track:
board: A 3x3 grid (initialized withNone).next_player: A string tracking whose turn it is (initialized to'X').moves: A counter for successfully placed marks (initialized to0).finished: A boolean flag indicating whether a terminal state ("Win"or"Draw") has been reached.
For each (operation, args) pair:
- Validation: If
operation != "move", or iffinishedisTrue, or ifplayer != next_player, or if(row, col)is out of bounds or already filled, record"Invalid". Note that rejected commands must leave all state variables unchanged. - State Update: If valid, record the player mark at
board[row][col]and incrementmoves. - Outcome Determination:
- Check for a 3-in-a-row along the updated row, column, main diagonal (if
row == col), or anti-diagonal (ifrow + col == 2). If detected, markfinished = Trueand record"Win". - Otherwise, if
moves == 9, markfinished = Trueand record"Draw". - Otherwise, swap
next_player(between'X'and'O') and record"Success".
- Check for a 3-in-a-row along the updated row, column, main diagonal (if
Complexity Analysis
- Time Complexity: $\mathcal{O}(1)$ per move operation since board size is fixed ($3 \times 3$). For $N$ operations total, the time complexity is $\mathcal{O}(N)$.
- Space Complexity: $\mathcal{O}(1)$ auxiliary space for internal game state representation, plus $\mathcal{O}(N)$ space to build the result list.
Python 3 Source Code
from typing import List, Optional
def tic_tac_toe(operations: List[str], arguments: List[List]) -> List[Optional[str]]:
board = [[None] * 3 for _ in range(3)]
next_player = 'X'
moves = 0
finished = False
results = []
for operation, args in zip(operations, arguments):
if operation != 'move':
results.append('Invalid')
continue
row, col, player = args
if (finished or player != next_player or player not in ('X', 'O')
or not (0 <= row < 3 and 0 <= col < 3)
or board[row][col] is not None):
results.append('Invalid')
continue
board[row][col] = player
moves += 1
won = (
all(board[row][c] == player for c in range(3))
or all(board[r][col] == player for r in range(3))
or (row == col and all(board[i][i] == player for i in range(3)))
or (row + col == 2 and all(board[i][2 - i] == player for i in range(3)))
)
if won:
finished = True
results.append('Win')
elif moves == 9:
finished = True
results.append('Draw')
else:
next_player = 'O' if player == 'X' else 'X'
results.append('Success')
return results