Simulate a Nested Tic-Tac-Toe Game with Board-Routing Rules
Data Structure DesignAuto-graded · 14 test casesLast updated
Tests state management for a two-layer game board with recursive win detection and dynamic move constraints based on previous plays.
Problem Statement
You are building a simulator for a variant of tic-tac-toe played on a nested grid. The game board contains nine smaller 3×3 grids arranged in a 3×3 layout, creating 81 total cells.
Gameplay follows these rules:
- Two players alternate turns, placing their symbol (X or O) in empty cells.
- When a player marks a cell within a small grid, the position of that cell dictates which small grid the opponent must use for their next move. For instance, marking the top-right cell of any small grid forces the next player to move somewhere within the top-right small grid of the overall layout.
- If the required small grid is unavailable (already won or completely filled), the next player may choose any cell in any available small grid.
- A small grid is won when a player achieves three of their symbols in a row—horizontally, vertically, or diagonally—within that grid. Once won, the entire small grid is closed to further moves.
- The overall game is won by capturing three small grids in a row (horizontally, vertically, or diagonally) on the meta-level 3×3 arrangement of small grids.
Implement a function that processes a sequence of operations on this game:
"UltimateTicTacToe": Initialize the game state (returnsNone)."make_move": Attempt a move given[board_idx, cell_idx]where both indices are 0-8. ReturnsTrueif the move is valid and applied,Falseotherwise."check_winner": Returns'X'if X has won,'O'if O has won,'Draw'if all small grids are complete with no overall winner, orNoneif the game is still in progress.
Both board_idx and cell_idx use row-major ordering (0=top-left, 1=top-center, ..., 8=bottom-right).
A move is invalid if:
- The game has already concluded
- Either index is out of range [0, 8] or not an integer
- The move is to a board other than the required one (when a specific board is mandated)
- The target small grid has already been won
- The target cell is already occupied
Invalid moves do not change any game state and do not advance the turn.
Constraints
board_idxandcell_idxare in the range [0, 8]- The first move may be placed in any cell of any small grid
- X always moves first
- Operations are processed in the order given
- The function must handle all invalid move scenarios by returning
Falsewithout mutating state
Examples
Example 1
Input: nested_tictactoe_game(['UltimateTicTacToe', 'make_move', 'make_move', 'check_winner'], [[], [0, 4], [4, 0], []])
Output: [None, True, True, None]
Example 2
Input: nested_tictactoe_game(['UltimateTicTacToe', 'make_move', 'make_move', 'make_move', 'check_winner'], [[], [0, 4], [4, 0], [0, 1], []])
Output: [None, True, True, True, None]
Hints
Hint 1
Track which player's turn it is separately from the board state, and only advance the turn when a valid move is made.
Hint 2
A single helper function can detect three-in-a-row on any 9-element list, allowing you to reuse it for both small grid victories and the overall meta-grid victory.
Hint 3
After each valid move, determine whether the destination small grid is playable—if it's already won or full, the next player gets free choice of any open grid.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution manages a two-level game structure where small tic-tac-toe grids exist within a meta-grid, each level following identical winning rules.
We maintain four key pieces of state:
- Small grid cells: A 9×9 structure storing each player's marks across all 81 cells
- Grid winners: A length-9 list tracking which player (if any) has won each small grid
- Current player: Tracks whose turn it is (starts with X)
- Required grid: Records which small grid must be used for the next move, or
Nonefor free choice
The core insight is that win detection works identically at both levels. A single helper function checks all eight possible three-in-a-row patterns on any list of nine values. We call it on a small grid's cells to determine that grid's winner, and on the grid winners list to determine the overall game winner.
Move Processing
When processing a move to position (grid_pos, cell_pos):
-
Validate: Check that the game isn't over, indices are valid integers in range, the move respects any grid requirement, the target small grid isn't already won, and the cell isn't occupied. Invalid moves return
Falsewithout changing state. -
Apply the mark: Place the current player's symbol in the specified cell.
-
Update the small grid winner: Recompute the winner for only the affected small grid (other grids are unchanged).
-
Determine the next requirement: The cell position becomes the next required grid index. If that grid is still playable (not won and has empty cells), enforce it as required. Otherwise, set no requirement.
-
Switch players: Alternate to the other player.
Game Status
The overall status is computed by:
- Checking if any player has three small grid wins in a row (meta-level victory)
- If no meta-level winner exists, checking if all small grids are complete (either won or fully filled), which indicates a draw
- Otherwise, returning
Nonefor an ongoing game
A small grid that fills without a winner remains a None in the grid winners list, effectively a "dead" cell that neither player can use to win the meta-game.
Why This Works
The forced-grid mechanism is updated immediately after each move based on current board state. This naturally handles the edge case where a player wins the small grid they were sent to—since that grid is now won, the opponent gets free choice.
Invalid moves never mutate state, preserving proper turn alternation. The turn counter only advances on successful moves, ensuring X and O alternate correctly through the game.
Complexity
Time: O(1) per operation. Each move checks eight patterns across nine cells for the local winner and scans one small grid to determine routing. Status checks examine all nine grids (81 cells total), but this is still constant.
Space: O(1) since we store exactly 81 cells plus a constant amount of metadata.
Solution
from typing import List
def nested_tictactoe_game(operations: List[str], arguments: List[List[int]]) -> List[object]:
winning_patterns = (
(0, 1, 2), (3, 4, 5), (6, 7, 8),
(0, 3, 6), (1, 4, 7), (2, 5, 8),
(0, 4, 8), (2, 4, 6)
)
small_grids = [[None] * 9 for _ in range(9)]
grid_winners = [None] * 9
current_player = 'X'
required_grid = None
output = []
def find_winner(marks):
for i, j, k in winning_patterns:
if marks[i] is not None and marks[i] == marks[j] == marks[k]:
return marks[i]
return None
def overall_status():
meta_winner = find_winner(grid_winners)
if meta_winner is not None:
return meta_winner
all_complete = all(
grid_winners[idx] is not None or all(cell is not None for cell in small_grids[idx])
for idx in range(9)
)
if all_complete:
return 'Draw'
return None
for op, params in zip(operations, arguments):
if op == 'UltimateTicTacToe':
output.append(None)
elif op == 'make_move':
grid_pos, cell_pos = params
status = overall_status()
is_invalid = (
status is not None
or not isinstance(grid_pos, int) or not isinstance(cell_pos, int)
or not (0 <= grid_pos < 9 and 0 <= cell_pos < 9)
or (required_grid is not None and grid_pos != required_grid)
or grid_winners[grid_pos] is not None
or small_grids[grid_pos][cell_pos] is not None
)
if is_invalid:
output.append(False)
continue
small_grids[grid_pos][cell_pos] = current_player
grid_winners[grid_pos] = find_winner(small_grids[grid_pos])
destination_available = (
grid_winners[cell_pos] is None
and any(cell is None for cell in small_grids[cell_pos])
)
required_grid = cell_pos if destination_available else None
current_player = 'O' if current_player == 'X' else 'X'
output.append(True)
elif op == 'check_winner':
output.append(overall_status())
else:
raise ValueError('Unknown operation')
return output