Enumerating Tic-Tac-Toe Move Sequences by Outcome

Hard · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Two players, 'X' and 'O', alternate turns placing their symbol on an unoccupied cell ('.') of a 3 x 3 Tic-Tac-Toe grid. Starting from a blank grid, 'X' takes the opening turn.

A completed game trajectory is the chronological sequence of placements made from the starting grid until play halts. Play halts on the exact turn when either condition below first holds:

  1. The player who just moved forms three matching symbols along any horizontal row, vertical column, or main/anti-diagonal, earning a win for that player (even if that move fills the ninth square).
  2. Every square on the grid is filled without either player forming three in a line, resulting in a draw.

No further placements are permitted once a trajectory halts. Two trajectories count as distinct whenever their move order differs at one or more turns, even when both end on the exact same 3 x 3 grid layout.

Implement:

def count_tic_tac_toe_games(
    board: Optional[List[List[str]]] = None,
    turn: str = "X",
) -> Dict[str, int]:

Given an ongoing grid configuration board (containing 'X', 'O', and '.') and the symbol turn ('X' or 'O') of the side to move next, compute how many distinct completed trajectories finish in each outcome from that point onward. When board is None, begin from an all-'.' 3 x 3 grid (turn defaults to 'X').

Return a dictionary with four integer entries:

  • 'X': number of distinct trajectories won by 'X'
  • 'O': number of distinct trajectories won by 'O'
  • 'Draw': number of distinct trajectories ending in a draw
  • 'Total': sum of all completed trajectories ('X' + 'O' + 'Draw')

Compute all counts algorithmically by traversing the state space rather than returning hard-coded constants.

Examples

Example 1

board = [
    ["X", ".", "O"],
    ["O", "X", "."],
    ["X", "O", "."],
]
count_tic_tac_toe_games(board, "X")
# -> {'X': 3, 'O': 0, 'Draw': 2, 'Total': 5}

Walk-through ('X' to play with three open squares (0, 1), (1, 2), and (2, 2)):

  • Playing (2, 2) completes the main diagonal (0, 0)-(1, 1)-(2, 2) right away, ending the game immediately (1 win for 'X'; the other two open squares are never played).
  • Playing (0, 1) leaves (1, 2) and (2, 2) for 'O': if 'O' picks (1, 2), 'X' takes (2, 2) on the final square to win; if 'O' blocks at (2, 2), 'X' fills (1, 2) for a draw (1 'X' win, 1 'Draw').
  • Playing (1, 2) behaves symmetrically: 'O' at (0, 1) lets 'X' win at (2, 2), while 'O' at (2, 2) leads to a draw after 'X' takes (0, 1) (1 'X' win, 1 'Draw').

Adding the branches gives {'X': 3, 'O': 0, 'Draw': 2, 'Total': 5}.

Example 2

board = [
    ["X", "X", "."],
    ["O", "O", "."],
    [".", ".", "X"],
]
count_tic_tac_toe_games(board, "O")
# -> {'X': 4, 'O': 9, 'Draw': 4, 'Total': 17}

Walk-through ('O' to play with four open squares (0, 2), (1, 2), (2, 0), and (2, 1)):

  • Playing (1, 2) completes row 1 (O, O, O) immediately (1 win for 'O', cutting off the remaining three empty cells).
  • Playing (0, 2) blocks 'X''s top-row threat and yields 4 'O' wins and 2 draws across 'X''s three replies.
  • Playing (2, 0) yields 2 'X' wins and 3 'O' wins.
  • Playing (2, 1) yields 2 'X' wins, 1 'O' win, and 2 draws.

Summing across all four opening choices gives {'X': 4, 'O': 9, 'Draw': 4, 'Total': 17}.

Constraints

  • board is either None or a 3 x 3 list of lists whose elements belong to {'X', 'O', '.'}.
  • Every provided board is a valid, non-terminal position (neither side already has three in a line, and at least one '.' cell remains).
  • turn is 'X' or 'O'.
  • Calling count_tic_tac_toe_games() from the blank grid must finish within 2.0 seconds.

Step-by-step walkthrough

  1. Understand what counts as a distinct game

    We want to count every distinct move sequence [move_1, move_2, ..., move_k] from a given non-terminal 3x3 Tic-Tac-Toe board, grouped into 'X', 'O', 'Draw', and 'Total'.

    Two rules shape the entire count:

    1. Move order matters: X at (0,0), O at (1,1), X at (0,1) is a different game sequence from X at (0,1), O at (1,1), X at (0,0), even though both sequences produce the exact same board after move 3.
    2. Games stop immediately on a win: the instant a mark completes 3-in-a-row, no further moves are legal. In Example 1 (X . O / O X . / X O . with X to move), playing (2,2) completes the main diagonal right away, so the remaining two open squares are never filled—collapsing those 2 permutations into 1 finished game and giving Total = 5 rather than 3! = 6.
  2. Start from backtracking over every legal move

    How do we explore every legal move sequence? With backtracking—a depth-first search (DFS) that places the current player's mark on an empty cell, checks whether the game just ended, recursively explores the opponent's replies if not, and then erases the mark (".") before trying the next empty cell.

    Plain backtracking is completely accurate, and from the empty board it visits all 255,168 legal games (549,945 total moves). However, it repeats the same work many times because different opening orders keep landing on the exact same mid-game board.

  3. Key idea: cache future game counts per board state

    Look at what happens when two different 3-move openings reach the exact same board with "O" to move:

      Path A: X@(0,0) -> O@(1,1) -> X@(0,1) \
                                             +--> Board: XX. / .O. / ... (O to move)
      Path B: X@(0,1) -> O@(1,1) -> X@(0,0) /        |
                                                     +--> Same remaining subtree!
    

    Once we know how many 'X' wins, 'O' wins, and 'Draw' games can finish starting from XX. / .O. / ... with "O" to move, that answer depends only on the current board and whose turn it is—never on whether we arrived via Path A or Path B!

    So we use memoization (storing each state's {"X", "O", "Draw"} counts in a dictionary memo the first time we compute them, and reusing that dictionary on later visits):

    • Notice the crucial difference between memoizing counts and a visited set: a visited set skips the state on Path B (counting those endings only once instead of twice), whereas returning the cached counts adds all those endings again for Path B! Every distinct move sequence is counted, while each of the 4,520 reachable non-terminal boards is solved only once.
  4. Check only the winning lines through the newest move

    Flattening the 3x3 board into a 9-element list cells (row * 3 + col) gives clean integer indices 0..8:

      0 | 1 | 2      rows:      (0,1,2), (3,4,5), (6,7,8)
     ---+---+---     columns:   (0,3,6), (1,4,7), (2,5,8)
      3 | 4 | 5      diagonals: (0,4,8), (2,4,6)
     ---+---+---
      6 | 7 | 8
    

    Because the board before a move had no winner, a newly completed 3-in-a-row must pass through the square moved_cell that was just played. Precomputing LINES_BY_CELL[moved_cell] lets completes_winning_line check only the 2, 3, or 4 lines touching moved_cell instead of all 8 lines.

    WINNING_LINES = [
        (0, 1, 2), (3, 4, 5), (6, 7, 8),  # 3 horizontal rows
        (0, 3, 6), (1, 4, 7), (2, 5, 8),  # 3 vertical columns
        (0, 4, 8), (2, 4, 6),             # 2 diagonals
    ]
    
    # LINES_BY_CELL[cell_idx] -> list of winning lines passing through `cell_idx` (2, 3, or 4 lines).
    LINES_BY_CELL: List[List[Tuple[int, int, int]]] = [[] for _ in range(9)]
    for _line in WINNING_LINES:
        for _cell_idx in _line:
            LINES_BY_CELL[_cell_idx].append(_line)
    
    
    def next_player(player: str) -> str:
        """Return the opposing player's mark."""
        if player == "X":
            return "O"
        return "X"
    
    
    def completes_winning_line(cells: List[str], moved_cell: int, player: str) -> bool:
        """Return True if placing `player` at `moved_cell` just completed 3-in-a-row."""
        for a, b, c in LINES_BY_CELL[moved_cell]:
            if cells[a] == player and cells[b] == player and cells[c] == player:
                return True
        return False
    
  5. Write the memoized backtracking search and public wrapper

    In count_from_state, we key memo by "".join(cells) + current_turn. For each empty cell, we place current_turn, check win first and full-board draw second (since a 9th-move 3-in-a-row is a win, not a draw), recurse only when the game is still ongoing, and always reset cells[cell_idx] = "." afterward.

    In count_tic_tac_toe_games, we copy the input 2D board into a fresh cells list so in-place backtracking never modifies the caller's list.

    def count_from_state(
        cells: List[str],
        current_turn: str,
        memo: Dict[str, Dict[str, int]],
    ) -> Dict[str, int]:
        """Count completed game sequences starting from this non-terminal board state."""
        state_key = "".join(cells) + current_turn
        if state_key in memo:
            return memo[state_key]
    
        counts = {"X": 0, "O": 0, "Draw": 0}
    
        for cell_idx in range(9):
            if cells[cell_idx] != ".":
                continue
    
            # Phase 1: Make the move in place.
            cells[cell_idx] = current_turn
    
            # Phase 2: Check win BEFORE draw (a 9th-move 3-in-a-row is a win, not a draw).
            if completes_winning_line(cells, cell_idx, current_turn):
                counts[current_turn] += 1
            elif "." not in cells:
                counts["Draw"] += 1
            else:
                child_counts = count_from_state(cells, next_player(current_turn), memo)
                counts["X"] += child_counts["X"]
                counts["O"] += child_counts["O"]
                counts["Draw"] += child_counts["Draw"]
    
            # Phase 3: Undo the move (backtrack) so the next iteration starts from a clean board.
            cells[cell_idx] = "."
    
        memo[state_key] = counts
        return counts
    
    
    def count_tic_tac_toe_games(
        board: Optional[List[List[str]]] = None,
        turn: str = "X",
    ) -> Dict[str, int]:
        cells: List[str] = []
        if board is None:
            cells = ["."] * 9
        else:
            for row in board:
                for mark in row:
                    if mark == "X" or mark == "O":
                        cells.append(mark)
                    else:
                        cells.append(".")
    
        memo: Dict[str, Dict[str, int]] = {}
        counts = count_from_state(cells, turn, memo)
        total_games = counts["X"] + counts["O"] + counts["Draw"]
    
        return {
            "X": counts["X"],
            "O": counts["O"],
            "Draw": counts["Draw"],
            "Total": total_games,
        }
    
  6. Trace Example 1 as a complete game tree

    Let's trace Example 1 (X . O / O X . / X O ., with X to move on open cells (0,1), (1,2), (2,2)):

    Start: X . O / O X . / X O .  (X to move)
     |
     +-- X plays (0,1) -> no win; O to move on (1,2), (2,2)
     |    +-- O plays (1,2) -> no win; X plays (2,2) -> main diag X,X,X   -> [X wins]
     |    +-- O plays (2,2) -> no win; X plays (1,2) -> full board, no 3  -> [Draw]
     |
     +-- X plays (1,2) -> no win; O to move on (0,1), (2,2)
     |    +-- O plays (0,1) -> no win; X plays (2,2) -> main diag X,X,X   -> [X wins]
     |    +-- O plays (2,2) -> no win; X plays (0,1) -> full board, no 3  -> [Draw]
     |
     +-- X plays (2,2) -> main diag (0,0)-(1,1)-(2,2) is X,X,X -> STOP!   -> [X wins]
    

    Counting the five leaves gives X: 3, O: 0, Draw: 2, and Total: 5.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # All 8 winning 3-in-a-row lines as indices into a flat 9-cell list (row-major):
    #   0 | 1 | 2
    #  ---+---+---
    #   3 | 4 | 5
    #  ---+---+---
    #   6 | 7 | 8
    WINNING_LINES = [
        (0, 1, 2), (3, 4, 5), (6, 7, 8),  # 3 horizontal rows
        (0, 3, 6), (1, 4, 7), (2, 5, 8),  # 3 vertical columns
        (0, 4, 8), (2, 4, 6),             # 2 diagonals
    ]
    
    # LINES_BY_CELL[cell_idx] -> list of winning lines passing through `cell_idx` (2, 3, or 4 lines).
    LINES_BY_CELL: List[List[Tuple[int, int, int]]] = [[] for _ in range(9)]
    for _line in WINNING_LINES:
        for _cell_idx in _line:
            LINES_BY_CELL[_cell_idx].append(_line)
    
    
    def next_player(player: str) -> str:
        """Return the opposing player's mark."""
        if player == "X":
            return "O"
        return "X"
    
    
    def completes_winning_line(cells: List[str], moved_cell: int, player: str) -> bool:
        """Return True if placing `player` at `moved_cell` just completed 3-in-a-row."""
        # Because the board before the move was non-terminal, only a line containing
        # `moved_cell` could have become complete on this turn.
        for a, b, c in LINES_BY_CELL[moved_cell]:
            if cells[a] == player and cells[b] == player and cells[c] == player:
                return True
        return False
    
    
    def count_from_state(
        cells: List[str],
        current_turn: str,
        memo: Dict[str, Dict[str, int]],
    ) -> Dict[str, int]:
        """Count completed game sequences starting from this non-terminal board state."""
        # memo maps "9-char board + player to move" -> {"X": int, "O": int, "Draw": int}.
        # How we reached this board does not change how many future sequences finish from here.
        state_key = "".join(cells) + current_turn
        if state_key in memo:
            return memo[state_key]
    
        counts = {"X": 0, "O": 0, "Draw": 0}
    
        # Try placing `current_turn` on every currently empty cell.
        for cell_idx in range(9):
            if cells[cell_idx] != ".":
                continue
    
            # Phase 1: Make the move in place.
            cells[cell_idx] = current_turn
    
            # Phase 2: Check win BEFORE draw (a 9th-move 3-in-a-row is a win, not a draw).
            if completes_winning_line(cells, cell_idx, current_turn):
                # Game terminates immediately upon a win; do not fill remaining empty cells.
                counts[current_turn] += 1
            elif "." not in cells:
                counts["Draw"] += 1
            else:
                child_counts = count_from_state(cells, next_player(current_turn), memo)
                counts["X"] += child_counts["X"]
                counts["O"] += child_counts["O"]
                counts["Draw"] += child_counts["Draw"]
    
            # Phase 3: Undo the move (backtrack) so the next iteration starts from a clean board.
            cells[cell_idx] = "."
    
        memo[state_key] = counts
        return counts
    
    
    def count_tic_tac_toe_games(
        board: Optional[List[List[str]]] = None,
        turn: str = "X",
    ) -> Dict[str, int]:
        # Flatten into a fresh 9-element list so backtracking never mutates the caller's board.
        cells: List[str] = []
        if board is None:
            cells = ["."] * 9
        else:
            for row in board:
                for mark in row:
                    if mark == "X" or mark == "O":
                        cells.append(mark)
                    else:
                        cells.append(".")
    
        # memo: caches outcome counts per unique (board_string + next_turn) state.
        memo: Dict[str, Dict[str, int]] = {}
        counts = count_from_state(cells, turn, memo)
        total_games = counts["X"] + counts["O"] + counts["Draw"]
    
        return {
            "X": counts["X"],
            "O": counts["O"],
            "Draw": counts["Draw"],
            "Total": total_games,
        }
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine counting every distinct walking route from your front door to different landmarks across a city grid. Two routes that take different streets in the first two blocks and meet at the same intersection are still two distinct routes—yet once both routes stand at that exact intersection, the number of ways to finish the walk from there onward is identical. By solving each intersection once, writing its outcome counts on a signpost (memoization—caching a function's answer in a dictionary keyed by state so identical subproblems are never recomputed), and adding those saved counts whenever another route reaches that intersection, we count every single move sequence without re-exploring the rest of the game tree.

Plain backtracking (placing a mark, recursing on remaining moves, and erasing the mark afterward) without memoization works, because 3x3 Tic-Tac-Toe is finite, but it explores all 549,945 moves across 255,168 games by solving the same mid-game boards hundreds of times. On the other hand, using a plain visited set (which skips boards seen earlier) fails completely because it counts only one route through each board instead of adding the counts for every route that reaches it.

Walk through Example 1 (X . O / O X . / X O ., X to move on open squares (0, 1), (1, 2), and (2, 2)):

  • X plays (2, 2): Completes main diagonal X, X, X and stops immediately -> 1 game (X).
  • X plays (0, 1): Game continues; O can play (1, 2) (letting X take (2, 2) to win on move 9 -> X) or (2, 2) (forcing X at (1, 2) with no line -> Draw) -> 2 games (1 X, 1 Draw).
  • X plays (1, 2): Symmetric to (0, 1): O at (0, 1) lets X win at (2, 2) (X), while O at (2, 2) leaves X at (0, 1) for a Draw -> 2 games (1 X, 1 Draw).
  • Sum across all 3 choices: {'X': 3, 'O': 0, 'Draw': 2, 'Total': 5}.

Complexity

Let P be the number of distinct non-terminal (board, turn) states reachable from the input board (from the empty 3x3 board, P = 4,520, bounded in general by 3^9 = 19,683).

  • Time: O(P) state evaluations (at most 4,520 * 9 * 4 elementary checks on an empty 3x3 board). Each reachable non-terminal state is expanded at most once before being stored in memo; expanding a state loops over 9 cells and inspects at most 4 precomputed winning lines passing through the played cell, finishing in a few milliseconds in Python.
  • Space: O(P) for memo plus O(9) call-stack depth. memo stores one 3-entry dictionary for each of the P reachable non-terminal states, while the in-place cells list and recursion stack never exceed depth 9 (one frame per empty square).

Edge cases

  • board=None default: Initializes cells to nine "." entries and starts from turn ("X" by default), producing the classic empty-board counts {'X': 131184, 'O': 77904, 'Draw': 46080, 'Total': 255168}.
  • One empty square remaining: Tries the single legal move and returns Total = 1—either 1 win for turn if that final square completes a line, or 1 Draw otherwise.
  • Immediate win with empty squares still left: As soon as completes_winning_line returns True, the branch adds 1 to counts[current_turn] and does not recurse on the remaining "." squares.
  • Caller's board immutability: Copying board into a fresh flat cells list ensures backtracking never leaves temporary marks in, or mutates, the caller's 2D list.
  • Custom starting turn: Including current_turn in state_key ("".join(cells) + current_turn) keeps cached entries unambiguous for any valid (board, turn) input.

Common mistakes

  • Continuing to play after someone gets 3-in-a-row: Counting all k! permutations of the k empty squares ignores early game termination (for example, inflating Example 1's 5 legal trajectories into 6).
  • Using a visited set instead of caching outcome counts: Skipping a previously visited transposition (a board position reached via a different move order) counts its continuations once total instead of once per incoming move sequence.
  • Checking for a full board before checking for a win: Miscounts all 81,792 games where "X" wins on the 9th and final move as draws.
  • Forgetting to undo cells[cell_idx] = "." on terminal branches: Using return or continue after a win without restoring "." corrupts the board for sibling moves in the loop.
  • Mutating a cached dictionary inside memo: Once memo[state_key] = counts is saved, parent calls must copy/add values into their own fresh counts dictionary rather than modifying child_counts in place.

Follow-up questions

  • What changes if we want the number of unique ending grid layouts instead of ordered play histories? Here move order should be ignored, so a visited set of (board_string, turn) states plus a terminal_boards set is the exact right tool: skip any state already in visited so identical mid-game boards are never explored twice, and whenever a move wins or fills the board, add the resulting 9-character board string to terminal_boards[outcome]. Because sets automatically deduplicate boards reached through different move orders, starting from an empty 3x3 board yields 958 distinct final boards (626 won by X, 316 won by O, and 16 draws).
  • How could integer bitmasks replace the list-based grid to accelerate move updates and three-in-a-row checks? A bitboard packs a player's marks on the 9 squares into a single 9-bit integer (0 to 511), using one integer x_mask for "X" and one o_mask for "O". Finding empty squares is free = 0b111111111 & ~(x_mask | o_mask), picking and clearing the lowest empty square uses the bitwise trick bit = free & -free; free ^= bit, applying a move is new_mask = me | bit (requiring zero undo cleanup because integers are immutable), checking a win tests (new_mask & line_mask) == line_mask against 8 integer constants like 0b000000111, and (x_mask, o_mask) serves directly as a fast integer-tuple memo key without string joins.
  • On a larger N-by-N board requiring K marks in a line, full search blows up—how would you approximate the terminal sequence counts? Because 3^(N*N) states cannot fit in memory or time, use Knuth's Monte Carlo tree-size estimator—a randomized sampling method that plays out one random game at a time from the root, choosing uniformly among the b_d legal moves at each depth d until a win or draw occurs, and records the product W = b_0 * b_1 * ... * b_{L-1}. By probability, the expected value of W across random playouts equals the exact total number of terminal game sequences (and attributing W to the playout's winner unbiasedly estimates 'X', 'O', and 'Draw' separately); averaging thousands of independent playouts—optionally switching to exact memoized search once only a few empty cells remain—gives a fast, low-memory estimate with confidence intervals.

Follow-up questions

Similar questions

More Decagon interview questions

All 20 Decagon questions →