Nested 3x3 Ultimate Tic-Tac-Toe Engine
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Build the state engine for Ultimate Tic-Tac-Toe, played across nine 3 x 3 sub-boards arranged into a 3 x 3 outer grid (81 squares in total). Both sub-boards (board_idx) and squares inside a sub-board (cell_idx) are indexed 0 through 8 in row-major order (3 * row + col).
Gameplay Rules
- Alternating turns:
'X'takes the opening turn, and'X'and'O'alternate strictly on valid placements. On the very first turn,'X'may pick any square of any sub-board. - Sub-board redirection: When a valid placement is made at
(board_idx, cell_idx),cell_idxdictates the sub-board where the opponent must play next (next_board = cell_idx). - Resolved (closed) sub-boards and free turns: A sub-board is permanently resolved as soon as a player aligns three of their marks horizontally, vertically, or diagonally inside it (claiming that sub-board for
'X'or'O'), or when all9of its squares become occupied without three in a line. Once resolved, no additional marks may ever be placed inside that sub-board—even on leftover empty squares of a claimed sub-board. Whenever redirection points to a sub-board that is already resolved, the next player receives a free turn and may play in any empty square of any unresolved sub-board. - Illegal placements: A call to
make_move(board_idx, cell_idx)is invalid and returnsFalse(leaving turn order, board contents, and redirection state untouched) if the match has already ended, ifboard_idxorcell_idxlies outside0..8, if a forced sub-board applies andboard_idxdoes not match it, ifboard_idxis resolved, or if squarecell_idxis already occupied. - Match outcome: Claiming three sub-boards along any row, column, or diagonal of the
3 x 3outer grid immediately wins the match ('X'or'O'). If all nine sub-boards become resolved without three claimed sub-boards in a line, the match ends as'Draw'. While unresolved legal moves remain and nobody has won on the outer grid, the outcome isNone.
Interface
Implement UltimateTicTacToe and the operation driver ultimate_tic_tac_toe:
class UltimateTicTacToe:
def __init__(self) -> None: ...
def make_move(self, board_idx: int, cell_idx: int) -> bool: ...
def check_winner(self) -> Optional[str]: ...
def ultimate_tic_tac_toe(
operations: List[str], arguments: List[List[int]]
) -> List[object]:
Each (op, args) pair in (operations, arguments) runs one command and records its return value:
- "UltimateTicTacToe" with []: starts a new instance and records None.
- "make_move" with [board_idx, cell_idx]: calls make_move(board_idx, cell_idx) and records True or False.
- "check_winner" with []: calls check_winner() and records 'X', 'O', 'Draw', or None.
Examples
Example 1
Input:
operations = ["UltimateTicTacToe", "make_move", "make_move", "make_move", "check_winner"]
arguments = [[], [2, 6], [5, 1], [6, 2], []]
Output:
[None, True, False, True, None]
'X' opens at (2, 6), which succeeds (True) and directs 'O' to sub-board 6. 'O' next attempts (5, 1), which is rejected (False) because sub-board 6 is required; 'O' still holds the turn and plays (6, 2) (True). Neither player owns three outer sub-boards yet, so check_winner returns None.
Example 2
Input:
operations = [
"UltimateTicTacToe",
"make_move", "make_move", "make_move", "make_move",
"make_move", "make_move", "make_move", "make_move",
"check_winner"
]
arguments = [
[],
[1, 0], [0, 1], [1, 4], [4, 1],
[1, 8], [8, 1], [1, 2], [7, 3],
[]
]
Output:
[None, True, True, True, True, True, True, False, True, None]
'X' places marks in sub-board 1 at squares 0, 4, and 8 across turns 1, 3, and 5, claiming sub-board 1 on its main diagonal and directing 'O' to sub-board 8. When 'O' plays (8, 1), cell_idx = 1 points to the now-resolved sub-board 1, granting 'X' a free turn. 'X' tries (1, 2) (False, because sub-board 1 is closed despite square 2 being empty), then legally uses the free turn at (7, 3) (True). Only one sub-board has been claimed so far, so check_winner returns None.
Constraints
1 <= len(operations) == len(arguments) <= 10^4operations[0] == "UltimateTicTacToe"- Every
"make_move"call passes two integers[board_idx, cell_idx](note that tests may pass out-of-range integers such as-1or9to verify bounds checking).
Step-by-step walkthrough
Understand the nested board and redirection rule
Ultimate Tic-Tac-Toe arranges 9 ordinary 3×3 tic-tac-toe boards ("local boards") into one larger 3×3 grid (the meta-grid, where each local board acts as a single big square). Both
board_idx(which local board) andcell_idx(which square inside that local board) are numbered0through8row by row:Index layout (used for BOTH local boards 0..8 and cells 0..8 inside each board): 0 | 1 | 2 --+---+-- 3 | 4 | 5 --+---+-- 6 | 7 | 8 Redirection example: X plays make_move(board_idx=2, cell_idx=6) Board 2 (top-right) 3x3 Meta-Grid of local boards . | . | . Board 0 | Board 1 | [Board 2] --+---+-- ----------+-----------+---------- . | . | . ===> Board 3 | Board 4 | Board 5 --+---+-- ----------+-----------+---------- X | . | . (cell 6) [Board 6] | Board 7 | Board 8 (O must play in Board 6 next!)Let's pin down every rule clearly before writing code:
- Turn order:
'X'plays first, then'O'and'X'alternate on valid moves. - Redirection: Playing in
cell_idx = cforces the next player to play insideboard_idx = c. - Closed local boards: A local board becomes closed (complete) as soon as someone gets three in a row inside it or all 9 of its cells fill up. Nobody can ever place another mark inside a closed board—even if a won board still has empty cells. If a player is redirected to a closed board, they get a free move in any empty cell of any still-open local board.
- Invalid moves: Out-of-bounds indices, playing in the wrong board, playing in a closed board or occupied cell, or playing after the game has ended must return
Falseand leave every piece of game state unchanged. - Game outcome (
check_winner): Three local-board wins by the same player along a row, column, or diagonal of the meta-grid return'X'or'O'. If all 9 local boards are closed with no meta-grid winner, no legal move remains and the result is'Draw'. Otherwise the game is ongoing (None).
- Turn order:
Design the game state and reusable 3-in-a-row helper
A naive approach stores only the list of past moves and redraws a 9×9 grid from scratch on every call. While 81 cells are small enough that re-scanning works as a test sanity check, tracking the game state explicitly makes every rule transparent and runs in constant time.
Notice a helpful symmetry: a single local board is a 9-element list of
'X','O', orNone, and the 3×3 meta-grid of local board winners is also a 9-element list of'X','O', orNone. That means one helper functionfind_line_winner(grid)can check for three in a row at both levels!# WINNING_LINES: the 8 index triples (a, b, c) that form 3-in-a-row on a 3x3 grid numbered 0..8. WINNING_LINES = [ (0, 1, 2), (3, 4, 5), (6, 7, 8), # horizontal rows (0, 3, 6), (1, 4, 7), (2, 5, 8), # vertical columns (0, 4, 8), (2, 4, 6), # main and anti-diagonals ] def find_line_winner(grid: List[Optional[str]]) -> Optional[str]: """Return 'X' or 'O' if that mark fills any winning line of a 9-cell grid, else None.""" for a, b, c in WINNING_LINES: first_mark = grid[a] # Exclude None explicitly because None == None == None would falsely match an empty line. if first_mark is not None and first_mark == grid[b] == grid[c]: return first_mark return NoneChecking
first_mark is not Noneis essential: three empty squares all equalNone, so omitting that check would declareNone(or fail) on an empty line.Validate moves safely before touching any state
Inside
UltimateTicTacToe, we store: -cells[board_idx][cell_idx]:'X','O', orNone. -local_winner[board_idx]:'X','O', orNonefor each of the 9 local boards. -moves_in_board[board_idx]: integer0..9counting how many marks sit in that board, so checking whether a board is full is a single== 9comparison. -current_player:'X'or'O'. -required_board:0..8when the player is forced into one board, orNonewhen they have a free move. -result:'X','O','Draw', orNone.In
is_valid_move, the order of checks matters. In Python, negative indices likeself.cells[-1]silently access element8instead of raising an error, so we must check0 <= board_idx <= 8and0 <= cell_idx <= 8before indexing any list.class UltimateTicTacToe: def __init__(self): # cells: 9x9 list where cells[board_idx][cell_idx] is 'X', 'O', or None (empty). self.cells: List[List[Optional[str]]] = [[None] * 9 for _ in range(9)] # local_winner: length-9 list of 'X', 'O', or None representing the 3x3 meta-grid. self.local_winner: List[Optional[str]] = [None] * 9 # moves_in_board: length-9 list counting placed marks (0..9) inside each local board. self.moves_in_board: List[int] = [0] * 9 self.current_player: str = "X" # required_board: int 0..8 forcing the next board, or None when any open board is allowed. self.required_board: Optional[int] = None # result: 'X', 'O', 'Draw' once the game ends, or None while play is ongoing. self.result: Optional[str] = None def check_local_winner(self, board_idx: int) -> Optional[str]: """Return 'X' or 'O' if local board `board_idx` has three in a row, else None.""" return find_line_winner(self.cells[board_idx]) def is_board_closed(self, board_idx: int) -> bool: """Return True if local board `board_idx` is already won or has all 9 cells filled.""" has_winner = self.local_winner[board_idx] is not None is_full = self.moves_in_board[board_idx] == 9 return has_winner or is_full def is_valid_move(self, board_idx: int, cell_idx: int) -> bool: """Check every legality rule without modifying game state.""" # No moves are allowed after a player wins or the game draws. if self.result is not None: return False # Bounds check MUST precede list indexing because Python's list[-1] wraps to index 8. if not (0 <= board_idx <= 8 and 0 <= cell_idx <= 8): return False # If the previous move forced a target board, the player must play there. if self.required_board is not None and board_idx != self.required_board: return False # Won or full local boards are permanently closed, even if won boards still have empty cells. if self.is_board_closed(board_idx): return False return self.cells[board_idx][cell_idx] is NoneExecute a move in five ordered phases
Once
is_valid_movepasses,make_moveupdates the state in a deliberate sequence:- Reject illegal moves first so invalid calls leave
current_playerandrequired_boarduntouched. - Place the mark and update the local board (
moves_in_boardandlocal_winner). Because the board was open before this move, it had no prior winner. - Update
resulton the meta-grid: checkfind_line_winner(self.local_winner); if nobody won, check whether all 9 local boards are now closed ("Draw"). - Choose
required_boardfor the next player: set it tocell_idx, orNoneif boardcell_idxis closed. Crucially, this runs after Phase 2! Suppose X wins board 4 by playing in its center square (board_idx=4, cell_idx=4). Phase 2 marks board 4 as won, so Phase 4 seesis_board_closed(4) == Trueand gives O a free move (required_board = None) instead of trapping O inside the newly closed board 4. - Switch
current_playerbetween'X'and'O'.
class UltimateTicTacToe: # ... __init__, check_local_winner, is_board_closed, is_valid_move ... def make_move(self, board_idx: int, cell_idx: int) -> bool: # Phase 1: Reject illegal moves immediately so turn and required_board stay untouched. if not self.is_valid_move(board_idx, cell_idx): return False # Phase 2: Place the mark and update this local board's fill count and winner. self.cells[board_idx][cell_idx] = self.current_player self.moves_in_board[board_idx] += 1 self.local_winner[board_idx] = self.check_local_winner(board_idx) # Phase 3: Check whether the 3x3 meta-grid now has a winner or all 9 boards are closed. overall_winner = find_line_winner(self.local_winner) if overall_winner is not None: self.result = overall_winner else: all_boards_closed = True for b in range(9): if not self.is_board_closed(b): all_boards_closed = False break if all_boards_closed: self.result = "Draw" # Phase 4: Redirect the next player to board `cell_idx` unless that board is now closed. # Running this AFTER Phase 2 handles a move that closes its own target (e.g., board 4, cell 4). if self.is_board_closed(cell_idx): self.required_board = None else: self.required_board = cell_idx # Phase 5: Switch turns only after a valid move finishes updating the board. if self.current_player == "X": self.current_player = "O" else: self.current_player = "X" return True- Reject illegal moves first so invalid calls leave
Expose the winner and wire up the operation dispatcher
Because
make_movekeepsself.resultup to date after every valid move,check_winnersimply returnsself.resultinO(1)time. The top-level judge functionultimate_tic_tac_toetranslates each operation name and argument list into method calls onUltimateTicTacToe:def ultimate_tic_tac_toe(operations: List[str], arguments: List[List[int]]) -> List[object]: # Replay the sequence of class constructor and method calls for the automated judge. game: Optional[UltimateTicTacToe] = None results: List[object] = [] for op, args in zip(operations, arguments): if op == "UltimateTicTacToe": game = UltimateTicTacToe() results.append(None) elif op == "make_move": results.append(game.make_move(args[0], args[1])) elif op == "check_winner": results.append(game.check_winner()) else: raise ValueError(f"unknown operation: {op}") return resultsTrace Example 1 step by step
Let's trace
operations = ['UltimateTicTacToe', 'make_move', 'make_move', 'make_move', 'check_winner']witharguments = [[], [2, 6], [5, 1], [6, 2], []]:Step 0: UltimateTicTacToe() current_player = 'X', required_board = None, result = None -> returns None Step 1: make_move(2, 6) [X's turn, free choice of open board] Board 2 gets 'X' at cell 6 (bottom-left). Board 6 is still open. required_board becomes 6, current_player becomes 'O'. -> returns True Step 2: make_move(5, 1) [O's turn, forced into Board 6] board_idx == 5 != required_board (6) -> rejected immediately! required_board stays 6, current_player stays 'O'. -> returns False Step 3: make_move(6, 2) [O's turn, still forced into Board 6] board_idx == 6 matches required_board! Board 6 gets 'O' at cell 2. Board 2 is still open (only cell 6 is taken, no winner). required_board becomes 2, current_player becomes 'X'. -> returns True Step 4: check_winner() local_winner is still [None, ..., None], so result is None. -> returns NoneNotice how rejecting
(5, 1)at Step 2 leftcurrent_player = 'O'andrequired_board = 6completely untouched so'O'could make the legal move(6, 2)on Step 3.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple # WINNING_LINES: the 8 index triples (a, b, c) that form 3-in-a-row on a 3x3 grid numbered 0..8. WINNING_LINES = [ (0, 1, 2), (3, 4, 5), (6, 7, 8), # horizontal rows (0, 3, 6), (1, 4, 7), (2, 5, 8), # vertical columns (0, 4, 8), (2, 4, 6), # main and anti-diagonals ] def find_line_winner(grid: List[Optional[str]]) -> Optional[str]: """Return 'X' or 'O' if that mark fills any winning line of a 9-cell grid, else None.""" for a, b, c in WINNING_LINES: first_mark = grid[a] # Exclude None explicitly because None == None == None would falsely match an empty line. if first_mark is not None and first_mark == grid[b] == grid[c]: return first_mark return None class UltimateTicTacToe: def __init__(self): # cells: 9x9 list where cells[board_idx][cell_idx] is 'X', 'O', or None (empty). self.cells: List[List[Optional[str]]] = [[None] * 9 for _ in range(9)] # local_winner: length-9 list of 'X', 'O', or None representing the 3x3 meta-grid. self.local_winner: List[Optional[str]] = [None] * 9 # moves_in_board: length-9 list counting placed marks (0..9) inside each local board. self.moves_in_board: List[int] = [0] * 9 self.current_player: str = "X" # required_board: int 0..8 forcing the next board, or None when any open board is allowed. self.required_board: Optional[int] = None # result: 'X', 'O', 'Draw' once the game ends, or None while play is ongoing. self.result: Optional[str] = None def check_local_winner(self, board_idx: int) -> Optional[str]: """Return 'X' or 'O' if local board `board_idx` has three in a row, else None.""" return find_line_winner(self.cells[board_idx]) def is_board_closed(self, board_idx: int) -> bool: """Return True if local board `board_idx` is already won or has all 9 cells filled.""" has_winner = self.local_winner[board_idx] is not None is_full = self.moves_in_board[board_idx] == 9 return has_winner or is_full def is_valid_move(self, board_idx: int, cell_idx: int) -> bool: """Check every legality rule without modifying game state.""" # No moves are allowed after a player wins or the game draws. if self.result is not None: return False # Bounds check MUST precede list indexing because Python's list[-1] wraps to index 8. if not (0 <= board_idx <= 8 and 0 <= cell_idx <= 8): return False # If the previous move forced a target board, the player must play there. if self.required_board is not None and board_idx != self.required_board: return False # Won or full local boards are permanently closed, even if won boards still have empty cells. if self.is_board_closed(board_idx): return False return self.cells[board_idx][cell_idx] is None def make_move(self, board_idx: int, cell_idx: int) -> bool: # Phase 1: Reject illegal moves immediately so turn and required_board stay untouched. if not self.is_valid_move(board_idx, cell_idx): return False # Phase 2: Place the mark and update this local board's fill count and winner. self.cells[board_idx][cell_idx] = self.current_player self.moves_in_board[board_idx] += 1 self.local_winner[board_idx] = self.check_local_winner(board_idx) # Phase 3: Check whether the 3x3 meta-grid now has a winner or all 9 boards are closed. overall_winner = find_line_winner(self.local_winner) if overall_winner is not None: self.result = overall_winner else: all_boards_closed = True for b in range(9): if not self.is_board_closed(b): all_boards_closed = False break if all_boards_closed: self.result = "Draw" # Phase 4: Redirect the next player to board `cell_idx` unless that board is now closed. # Running this AFTER Phase 2 handles a move that closes its own target (e.g., board 4, cell 4). if self.is_board_closed(cell_idx): self.required_board = None else: self.required_board = cell_idx # Phase 5: Switch turns only after a valid move finishes updating the board. if self.current_player == "X": self.current_player = "O" else: self.current_player = "X" return True def check_winner(self) -> Optional[str]: return self.result def ultimate_tic_tac_toe(operations: List[str], arguments: List[List[int]]) -> List[object]: # Replay the sequence of class constructor and method calls for the automated judge. game: Optional[UltimateTicTacToe] = None results: List[object] = [] for op, args in zip(operations, arguments): if op == "UltimateTicTacToe": game = UltimateTicTacToe() results.append(None) elif op == "make_move": results.append(game.make_move(args[0], args[1])) elif op == "check_winner": results.append(game.check_winner()) else: raise ValueError(f"unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Think of Ultimate Tic-Tac-Toe as nine regular tic-tac-toe boards arranged into one big 3×3 "board of boards" called the meta-grid (a higher-level 3×3 grid where each square tracks who won one entire small board). Every move you make has two jobs at once: it places your 'X' or 'O' inside one small board, and the cell position you picked (say, 4 = center) acts like a compass arrow telling your opponent which small board they must play in next. Because both a small board and the meta-grid are 3×3 grids of 'X', 'O', or None, the exact same 8-line winner-checking function works at both levels!
Why does a naive flat-grid approach fall short? If you only store a flat 9×9 array of 81 cells without per-board state, every call has to re-scan sub-grids to figure out whether a small board was already won earlier (meaning its leftover empty cells are off-limits), whether a board filled up in a tie, and which board the next player is forced to use. Worse, mixing validation with state updates makes it easy to introduce bugs—such as flipping whose turn it is on a rejected move, or locking the next player into a board that the current move just finished closing.
Let's walk through a short 4-call sequence to see how the explicit state fields (cells, local_winner, required_board, and current_player) work together:
1. X plays (board=2, cell=6):
- Valid (opening move is free). Board 2 cell 6 = 'X'.
- Cell 6 points to Board 6, which is open -> required_board = 6, turn = 'O'.
2. O tries (board=5, cell=1):
- Invalid! required_board is 6, not 5 -> returns False.
- Nothing changes: required_board stays 6, turn stays 'O'.
3. O plays (board=6, cell=2):
- Valid. Board 6 cell 2 = 'O'.
- Cell 2 points to Board 2, which is still open -> required_board = 2, turn = 'X'.
4. Suppose later X wins Board 3 by playing (board=3, cell=3):
- Board 3 gets local_winner[3] = 'X' FIRST (so Board 3 is now closed).
- Then cell 3 checks is_board_closed(3) -> True -> required_board = None (O gets a free move!).
Complexity
Let Q be the total number of operations passed to ultimate_tic_tac_toe.
- Time:
O(1)per operation, andO(Q)total acrossQcalls. On a fixed 3×3-of-3×3 board,is_valid_moveperforms a handful of array lookups,make_movechecks the 8 winning lines of one local board, checks the 8 winning lines oflocal_winner, and scans at most 9 local boards to detect a draw, andcheck_winnersimply readsself.result. - Space:
O(1)for the game state (beyond theO(Q)output list). Each game stores a fixed 9×9cellstable (81 entries) plus two length-9 arrays (local_winnerandmoves_in_board) and three scalar fields.
Edge cases
- Opening move:
required_boardstarts atNone, so'X'may play in any cell0..8of any board0..8. - Negative or out-of-bounds indices (
-1,9): Rejected before any list lookup; otherwise Python's negative indexing (self.cells[-1]) would silently access board8. - Redirected to a won board (with empty cells remaining): Treated as closed, so
required_boardbecomesNone(free move), and nobody may ever fill the leftover empty cells of that won board. - Redirected to a full, tied local board: A small board can fill all 9 cells without three in a row (for example
X O X / X O X / O X O). Becausemoves_in_board[b] == 9,is_board_closed(b)isTrueand any player sent there gets a free move. - Self-closing move (
cell_idx == board_idx): If playing(4, 4)wins or fills board4, updatinglocal_winner[4]andmoves_in_board[4]before computingrequired_boardensuresis_board_closed(4)isTrueand grants a free move. - Moves after game over: Once
self.resultis'X','O', or'Draw', every subsequentmake_movereturnsFalseandcheck_winnercontinues returningself.result.
Common mistakes
- Mutating state before validation completes: Switching
current_playeror overwritingrequired_boardbefore verifying that the cell is empty and in the right board corrupts the game whenever a player clicks an illegal square. - Allowing moves in empty cells of an already-won local board: Once a local board has a winner, the rules treat that entire sub-board as a single resolved square of the meta-grid, so it is closed to further play.
- Checking equality without excluding
None: Writinggrid[a] == grid[b] == grid[c]withoutgrid[a] is not Nonematches three empty squares (None == None == None) on move 1. - Declaring
'Draw'only when all 81 cells are filled: Won local boards almost always have empty cells left inside them when they close, so a drawn game usually ends with far fewer than 81 marks on the grid. - Computing
required_boardbefore updatinglocal_winner: If you setrequired_board = cell_idxbefore recording that the current move just won or filled boardcell_idx, the next player gets permanently stuck with zero legal moves.
Alternative approaches
- Flat 9×9 grid: Store one 9×9 array where
(board_idx, cell_idx)maps torow = (board_idx // 3) * 3 + cell_idx // 3andcol = (board_idx % 3) * 3 + cell_idx % 3. That layout is convenient for rendering ASCII boards, though per-board lists map much more directly to the game's rules. - Bitboards: A bitboard packs a player's marks on a 9-cell board into a 9-bit integer (one bit per cell), so checking a winning line reduces to a single bitwise AND
(mask & line_mask) == line_mask. Game-playing AI engines use bitboards to search millions of states per second, at the cost of less readable interview code.
Follow-up questions
- How would you scale the state representation and win checks when both the outer grid and each inner board have size N by N? Sub-board and cell indices now run from
0toN^2 - 1, and placing atcell_idxstill directs the opponent toboard_idx = cell_idx. Instead of scanning allN^2squares of a sub-board after each move, maintain per-player line tallies for each sub-board'sNrows,Ncolumns, and 2 diagonals: placing a mark at(r = cell_idx // N, c = cell_idx % N)increments at most 4 tallies and claims the sub-board inO(1)time as soon as any tally reachesN. Apply the exact sameO(1)tally update on theN x Nmeta-grid whenever a sub-board is claimed, and track anopen_boardsinteger count (starting atN^2, decremented whenever a sub-board is claimed or hitsN^2marks) so draw detection staysO(1)while total memory scales toO(N^4)for theN^4squares. - What backend endpoints and concurrency controls would you put in place for an online two-player match? Keep the server authoritative so clients cannot spoof turns: expose
POST /gamesto create a match,GET /games/{id}to read the current board state plus a monotonically increasingversioninteger, andPOST /games/{id}/movesaccepting{board_idx, cell_idx, expected_version}. The server verifies that the authenticated caller holdscurrent_player's seat, checksexpected_version == game.versionvia optimistic concurrency control (rejecting stale or duplicate requests with HTTP409 Conflictwithout holding locks across network round-trips), executesmake_move, incrementsversion, and appends the move to an append-only event log (a sequential database table that enables replay and auditing). Finally, broadcast the updated state to both players over WebSockets or Server-Sent Events (SSE). - How would you record past moves so players can undo (and optionally redo) turns in O(1) time? Push a compact tuple
(board_idx, cell_idx, prev_required_board)onto ahistorystack (a last-in, first-out list) at the end of every acceptedmake_move. Because moves are only accepted on open sub-boards whileresult is None, we know without storing snapshots thatlocal_winner[board_idx]andresultwere bothNoneimmediately prior to the last move. Undoing inO(1)time pops the top tuple, clearscells[board_idx][cell_idx] = None, decrementsmoves_in_board[board_idx], resetslocal_winner[board_idx] = Noneandresult = None, restoresrequired_board = prev_required_board, and flipscurrent_playerback (pushing the popped tuple onto aredo_stackcleared on any new move if redo is supported).
Follow-up questions
- How would you scale the state representation and win checks when both the outer grid and each inner board have size N by N?
- What backend endpoints and concurrency controls would you put in place for an online two-player match?
- How would you record past moves so players can undo (and optionally redo) turns in O(1) time?
Similar questions
- 3x3 Tic-Tac-Toe Grid Winner Check
- LRU Cache With Value-Grouped Snapshots
- Backend Architecture for a Multi-Agent Fintech Assistant
- Multi-Agent Corpus Research and Grounded Charting Platform
- Design a Cited Q&A Assistant over SEC Filings
- 2D Max Pooling with Source Coordinates