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

  1. 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.
  2. Sub-board redirection: When a valid placement is made at (board_idx, cell_idx), cell_idx dictates the sub-board where the opponent must play next (next_board = cell_idx).
  3. 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 all 9 of 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.
  4. Illegal placements: A call to make_move(board_idx, cell_idx) is invalid and returns False (leaving turn order, board contents, and redirection state untouched) if the match has already ended, if board_idx or cell_idx lies outside 0..8, if a forced sub-board applies and board_idx does not match it, if board_idx is resolved, or if square cell_idx is already occupied.
  5. Match outcome: Claiming three sub-boards along any row, column, or diagonal of the 3 x 3 outer 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 is None.

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^4
  • operations[0] == "UltimateTicTacToe"
  • Every "make_move" call passes two integers [board_idx, cell_idx] (note that tests may pass out-of-range integers such as -1 or 9 to verify bounds checking).

Step-by-step walkthrough

  1. 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) and cell_idx (which square inside that local board) are numbered 0 through 8 row 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 = c forces the next player to play inside board_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 False and 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).
  2. 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', or None, and the 3×3 meta-grid of local board winners is also a 9-element list of 'X', 'O', or None. That means one helper function find_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 None
    

    Checking first_mark is not None is essential: three empty squares all equal None, so omitting that check would declare None (or fail) on an empty line.

  3. Validate moves safely before touching any state

    Inside UltimateTicTacToe, we store: - cells[board_idx][cell_idx]: 'X', 'O', or None. - local_winner[board_idx]: 'X', 'O', or None for each of the 9 local boards. - moves_in_board[board_idx]: integer 0..9 counting how many marks sit in that board, so checking whether a board is full is a single == 9 comparison. - current_player: 'X' or 'O'. - required_board: 0..8 when the player is forced into one board, or None when they have a free move. - result: 'X', 'O', 'Draw', or None.

    In is_valid_move, the order of checks matters. In Python, negative indices like self.cells[-1] silently access element 8 instead of raising an error, so we must check 0 <= board_idx <= 8 and 0 <= cell_idx <= 8 before 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 None
    
  4. Execute a move in five ordered phases

    Once is_valid_move passes, make_move updates the state in a deliberate sequence:

    1. Reject illegal moves first so invalid calls leave current_player and required_board untouched.
    2. Place the mark and update the local board (moves_in_board and local_winner). Because the board was open before this move, it had no prior winner.
    3. Update result on the meta-grid: check find_line_winner(self.local_winner); if nobody won, check whether all 9 local boards are now closed ("Draw").
    4. Choose required_board for the next player: set it to cell_idx, or None if board cell_idx is 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 sees is_board_closed(4) == True and gives O a free move (required_board = None) instead of trapping O inside the newly closed board 4.
    5. Switch current_player between '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
    
  5. Expose the winner and wire up the operation dispatcher

    Because make_move keeps self.result up to date after every valid move, check_winner simply returns self.result in O(1) time. The top-level judge function ultimate_tic_tac_toe translates each operation name and argument list into method calls on UltimateTicTacToe:

    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
    
  6. Trace Example 1 step by step

    Let's trace operations = ['UltimateTicTacToe', 'make_move', 'make_move', 'make_move', 'check_winner'] with arguments = [[], [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 None
    

    Notice how rejecting (5, 1) at Step 2 left current_player = 'O' and required_board = 6 completely untouched so 'O' could make the legal move (6, 2) on Step 3.

  7. 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, and O(Q) total across Q calls. On a fixed 3×3-of-3×3 board, is_valid_move performs a handful of array lookups, make_move checks the 8 winning lines of one local board, checks the 8 winning lines of local_winner, and scans at most 9 local boards to detect a draw, and check_winner simply reads self.result.
  • Space: O(1) for the game state (beyond the O(Q) output list). Each game stores a fixed 9×9 cells table (81 entries) plus two length-9 arrays (local_winner and moves_in_board) and three scalar fields.

Edge cases

  • Opening move: required_board starts at None, so 'X' may play in any cell 0..8 of any board 0..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 board 8.
  • Redirected to a won board (with empty cells remaining): Treated as closed, so required_board becomes None (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). Because moves_in_board[b] == 9, is_board_closed(b) is True and any player sent there gets a free move.
  • Self-closing move (cell_idx == board_idx): If playing (4, 4) wins or fills board 4, updating local_winner[4] and moves_in_board[4] before computing required_board ensures is_board_closed(4) is True and grants a free move.
  • Moves after game over: Once self.result is 'X', 'O', or 'Draw', every subsequent make_move returns False and check_winner continues returning self.result.

Common mistakes

  • Mutating state before validation completes: Switching current_player or overwriting required_board before 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: Writing grid[a] == grid[b] == grid[c] without grid[a] is not None matches 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_board before updating local_winner: If you set required_board = cell_idx before recording that the current move just won or filled board cell_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 to row = (board_idx // 3) * 3 + cell_idx // 3 and col = (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 0 to N^2 - 1, and placing at cell_idx still directs the opponent to board_idx = cell_idx. Instead of scanning all N^2 squares of a sub-board after each move, maintain per-player line tallies for each sub-board's N rows, N columns, 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 in O(1) time as soon as any tally reaches N. Apply the exact same O(1) tally update on the N x N meta-grid whenever a sub-board is claimed, and track an open_boards integer count (starting at N^2, decremented whenever a sub-board is claimed or hits N^2 marks) so draw detection stays O(1) while total memory scales to O(N^4) for the N^4 squares.
  • 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 /games to create a match, GET /games/{id} to read the current board state plus a monotonically increasing version integer, and POST /games/{id}/moves accepting {board_idx, cell_idx, expected_version}. The server verifies that the authenticated caller holds current_player's seat, checks expected_version == game.version via optimistic concurrency control (rejecting stale or duplicate requests with HTTP 409 Conflict without holding locks across network round-trips), executes make_move, increments version, 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 a history stack (a last-in, first-out list) at the end of every accepted make_move. Because moves are only accepted on open sub-boards while result is None, we know without storing snapshots that local_winner[board_idx] and result were both None immediately prior to the last move. Undoing in O(1) time pops the top tuple, clears cells[board_idx][cell_idx] = None, decrements moves_in_board[board_idx], resets local_winner[board_idx] = None and result = None, restores required_board = prev_required_board, and flips current_player back (pushing the popped tuple onto a redo_stack cleared on any new move if redo is supported).

Follow-up questions

Similar questions

More Hebbia interview questions

All 6 Hebbia questions →