Game-Tree Enumeration for 4x4 Three-in-a-Row

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Two players, "X" and "O", play a generalized k-in-a-row game on a rectangular grid of rows by cols squares (by default, a 4 x 4 grid where k = 3 aligned marks win). Squares are numbered in row-major order so coordinate (r, c) (0 <= r < rows, 0 <= c < cols) has integer index r * cols + c.

Starting from a blank grid, "X" places the first mark (turn 0) and "O" places the second (turn 1), strictly alternating on unoccupied squares until the match reaches a terminal state:

  • Immediate win ("X" or "O"): As soon as the latest placement completes at least one contiguous segment of k matching marks along a horizontal row, vertical column, main diagonal (down-right), or anti-diagonal (down-left), that mover wins immediately and no further turns are played. On a 4 x 4 grid with k = 3, three consecutive marks suffice (a 4-square row or column contains two overlapping 3-square windows), and a single move completing two k-square windows at once still counts as one win.
  • Full-grid draw ("draw"): Every square (rows * cols turns) is filled without either player ever completing k consecutive marks. If the very last unoccupied square completes k consecutive marks, that placement is a win, not a draw.

A game sequence is the ordered tuple of square indices played from turn 0 through the terminal turn. Two play-throughs that fill the same squares in different turn orders (or reach rotated/reflected layouts) count as distinct game sequences.

Implement the following five functions using bitmasks, recursion, backtracking, and state memoization:

  • winning_lines(rows: int, cols: int, k: int) -> List[int]: Return a list containing one unique integer bitmask for every contiguous k-square line (horizontal, vertical, and both diagonal directions), where square i corresponds to bit 1 << i. Return [] if k <= 0 or no k-square line fits on the grid.
  • lines_through_cells(rows: int, cols: int, k: int) -> List[List[int]]: Return a list of length rows * cols whose i-th entry contains all bitmasks from winning_lines(rows, cols, k) that pass through square i.
  • count_games(rows: int = 4, cols: int = 4, k: int = 3) -> Tuple[int, int, int]: Use plain recursion and backtracking to return (x_wins, o_wins, draws), the exact counts of valid ordered game sequences ending in each outcome.
  • enumerate_games(rows: int = 3, cols: int = 3, k: int = 3) -> Iterator[Tuple[Tuple[int, ...], str]]: Lazily yield (moves, outcome) one game at a time (as a generator, without building a list in memory), trying available squares in ascending index order 0, 1, ..., rows * cols - 1, where outcome is "X", "O", or "draw".
  • count_games_memo(rows: int = 4, cols: int = 4, k: int = 3) -> Tuple[int, int, int]: Return the exact same (x_wins, o_wins, draws) sequence totals as count_games, caching continuation counts per non-terminal board state so 3 x 3 and 4 x 4 grids finish quickly.

Examples

Example 1

Input: rows = 1, cols = 4, k = 2

Output: - winning_lines(1, 4, 2) -> [3, 6, 12] - count_games(1, 4, 2) and count_games_memo(1, 4, 2) -> (12, 4, 8) - First three items from enumerate_games(1, 4, 2): 1. ((0, 1, 2, 3), "draw") 2. ((0, 1, 3, 2), "O") 3. ((0, 2, 1), "X")

Explanation: On the 4-square strip [0, 1, 2, 3], the adjacent pairs are {0, 1} (0b0011 = 3), {1, 2} (0b0110 = 6), and {2, 3} (0b1100 = 12). Exploring empty squares in ascending order: - 0 -> 1 -> 2 -> 3 produces [X, O, X, O] with no adjacent pair ("draw"). - Backtracking tries 0 -> 1 -> 3 -> 2, producing [X, O, O, X], where "O" completes {1, 2} on the final empty square ("O"). - Backtracking further tries 0 -> 2 -> 1, producing [X, X, O, .], where "X" completes {0, 1} on turn 3 and play halts immediately without filling square 3 ("X"). Across all branches there are 12 "X" wins, 4 "O" wins, and 8 draws.

Example 2

Input: rows = 2, cols = 3, k = 3

Output: - winning_lines(2, 3, 3) -> [7, 56] - lines_through_cells(2, 3, 3) -> [[7], [7], [7], [56], [56], [56]] - count_games(2, 3, 3) and count_games_memo(2, 3, 3) -> (72, 0, 648)

Explanation: Because columns and diagonals are at most 2 squares tall, only the two full 3-square rows can win: row 0 ({0, 1, 2} -> 1 + 2 + 4 = 7) and row 1 ({3, 4, 5} -> 8 + 16 + 32 = 56). For "X" to win on turn 5 (its third mark), "X" must claim one entire row (3! = 6 orders) while "O" places its first two marks in the opposite row (3 * 2 = 6 ordered choices), giving 2 * 6 * 6 = 72 "X" wins. "O" can never win on turn 6 because claiming an entire row of 3 would leave the other 3-square row completely held by "X" on turn 5; the remaining 648 sequences end in "draw".

Constraints

  • 1 <= rows, cols <= 4 and rows * cols <= 16.
  • 0 <= k <= 5 (if k <= 0 or k > max(rows, cols), no winning lines exist).
  • count_games is evaluated on small grids (rows * cols <= 9), whereas count_games_memo must handle up to 4 x 4 (16 squares).
  • enumerate_games must return a lazy iterator/generator (do not materialize all games in memory at once) and visit candidate squares in strictly increasing index order 0 .. rows * cols - 1.

Step-by-step walkthrough

  1. Clarify the rules and what counts as one game

    Before writing a single line of code, pin down the exact rules of the game. Changing any one of these definitions alters the final count by orders of magnitude:

    • We count ordered play-throughs, not unique final boards. A game is the ordered tuple of cell indices played from the empty board to the end. If X plays cell 0 then 5, that is a different game from X playing cell 5 then 0, even though the resulting board looks identical.
    • The game stops immediately on three-in-a-row. As soon as the latest move completes 3 consecutive marks horizontally, vertically, or diagonally, the mover wins and no more moves are played. Four-in-a-row never needs its own special rule because any 4 consecutive marks already contain two 3-cell windows, and a single move completing two 3-cell windows at once still counts as one win.
    • Check for a win before checking for a full board. If the 16th move fills the very last empty cell and completes 3-in-a-row, X or O won — it is not a draw.
    • Rotations and reflections are distinct games. Playing in the top-left corner (0, 0) and playing in the top-right corner (0, 3) count as separate games.
    • Output shape: we return (x_wins, o_wins, draws), whose sum is the grand total of valid games, and we also provide a lazy generator that streams (moves, outcome) one game at a time.

    Writing the functions for a general rows x cols board with k-in-a-row costs zero extra complexity and lets us verify our code on tiny boards (like 1 x 3 or 3 x 3) where we know the exact answer by hand.

  2. Number the cells and represent the board with bitmasks

    A bitmask is an ordinary integer whose binary digits (0 or 1) act as tiny on/off switches — one switch per cell on the board. Numbering the 16 cells of a 4 x 4 board row by row gives each (r, c) coordinate the single index r * cols + c:

    Cell indices on a 4 x 4 board:          Example line: row 0, cols 0..2
    +----+----+----+----+                   cells 0, 1, 2 -> bits 0, 1, 2 are 1:
    |  0 |  1 |  2 |  3 |                   mask = (1 << 0) | (1 << 1) | (1 << 2)
    +----+----+----+----+                        = 1 + 2 + 4 = 7  (binary 0b0111)
    |  4 |  5 |  6 |  7 |
    +----+----+----+----+                   Example line: diagonal (0,0)-(1,1)-(2,2)
    |  8 |  9 | 10 | 11 |                   cells 0, 5, 10 -> bits 0, 5, 10 are 1:
    +----+----+----+----+                   mask = (1 << 0) | (1 << 5) | (1 << 10)
    | 12 | 13 | 14 | 15 |                        = 1 + 32 + 1024 = 1057
    +----+----+----+----+
    

    We store the entire board as just two integers: x_mask (with bit i set to 1 whenever X occupies cell i) and o_mask (with bit i set to 1 whenever O occupies cell i). Then x_mask | o_mask has bit i set whenever cell i is occupied by either player.

    To precompute every winning line of length k, we try every starting cell (r, c) and step forward in 4 canonical directions: right (0, 1), down (1, 0), down-right (1, 1), and down-left (1, -1). Stepping in only one orientation per axis ensures we never generate the same line forwards and backwards. On a 4 x 4 board with k = 3, this produces 8 horizontal + 8 vertical + 4 down-right + 4 down-left = 24 winning line masks:

    from typing import Dict, Iterator, List, Tuple
    
    # Cell (r, c) is mapped to bit index (r * cols + c) of an integer bitmask.
    # Each winning line only needs to step forward in 4 directions so we never count a line twice:
    # right (0, 1), down (1, 0), down-right (1, 1), and down-left (1, -1).
    DIRECTIONS = [(0, 1), (1, 0), (1, 1), (1, -1)]
    
    
    def winning_lines(rows: int, cols: int, k: int) -> List[int]:
        """Bitmask of every run of k consecutive cells: horizontal, vertical, both diagonals."""
        if k <= 0:
            return []
        # When k == 1, a single cell is already a full line; using 1 direction avoids 4x duplicates.
        directions = [(0, 1)] if k == 1 else DIRECTIONS
        lines: List[int] = []
        for r in range(rows):
            for c in range(cols):
                for dr, dc in directions:
                    # Check whether the k-th cell from (r, c) still lands inside the board.
                    last_r = r + (k - 1) * dr
                    last_c = c + (k - 1) * dc
                    if 0 <= last_r < rows and 0 <= last_c < cols:
                        mask = 0
                        for step in range(k):
                            cell_index = (r + step * dr) * cols + (c + step * dc)
                            mask |= 1 << cell_index
                        lines.append(mask)
        return lines
    
  3. Check only the winning lines through the latest move

    Before a player places a mark on cell, the game was still in progress — neither player had three-in-a-row yet. Therefore, if the new move creates a winning line, that line must pass through cell. Instead of scanning all 24 lines after every move, we group the line masks by cell once up front:

    How many length-3 lines pass through each cell on a 4 x 4 board:
    +---+---+---+---+
    | 3 | 4 | 4 | 3 |    corners: 3 lines   (4 * 3 = 12)
    +---+---+---+---+    edges:   4 lines   (8 * 4 = 32)
    | 4 | 7 | 7 | 4 |    centers: 7 lines   (4 * 7 = 28)
    +---+---+---+---+    --------------------------------
    | 4 | 7 | 7 | 4 |    sum = 72 = 24 lines * 3 cells each
    +---+---+---+---+
    | 3 | 4 | 4 | 3 |
    +---+---+---+---+
    

    Testing whether a player's bitmask marks covers a line bitmask takes one bitwise AND: (marks & line) == line. Bitwise & keeps only the bits that are 1 in both integers, so the result equals line if and only if the player holds all k cells of that line:

    def lines_through_cells(rows: int, cols: int, k: int) -> List[List[int]]:
        """For each cell, the winning lines that contain it."""
        all_lines = winning_lines(rows, cols, k)
        # through[cell] holds the list of line bitmasks that include `cell`, e.g. [0b111, 0b1001001, ...].
        through: List[List[int]] = []
        for cell in range(rows * cols):
            cell_bit = 1 << cell
            containing_lines: List[int] = []
            for line in all_lines:
                if (line & cell_bit) != 0:
                    containing_lines.append(line)
            through.append(containing_lines)
        return through
    
    
    def is_win(marks: int, lines: List[int]) -> bool:
        """True if `marks` covers all cells of at least one bitmask in `lines`."""
        for line in lines:
            # (marks & line) == line holds iff every 1-bit in `line` is also 1 in `marks`.
            if (marks & line) == line:
                return True
        return False
    
  4. Explore the game tree with recursion and backtracking

    In game-tree search, one single turn by one player is called a ply. At depth = 0 (0 marks on the board), X makes the 1st move; at depth = 1, O makes the 2nd move; in general, player = depth % 2 (0 for X on even depths, 1 for O on odd depths).

    Backtracking means exploring every branch on a single shared board by following a strict three-step rhythm inside our loop over empty cells: 1. Make the move: set the bit board[player] |= cell_bit. 2. Check or recurse: if the move wins, add 1 to totals[player] and stop (do not recurse further); else if depth + 1 == n_cells, add 1 to totals[2] (a draw); else recurse to depth + 1. 3. Undo the move: flip that exact bit back off with board[player] ^= cell_bit so the board returns to its exact previous state before the loop tries the next empty cell.

    Here is the opening branch (X starts at square 0) on the Example 1 1 x 4 strip with k = 2 (squares 0, 1, 2, 3; winning line masks {0, 1}, {1, 2}, and {2, 3}):

    Start: [ . | . | . | . ] (depth 0, X to move)
      +-- X plays 0: [ X | . | . | . ]
            +-- O plays 1: [ X | O | . | . ]
            |     +-- X plays 2: [ X | O | X | . ] -> O plays 3: [ X | O | X | O ] (full -> DRAW)
            |     +-- X plays 3: [ X | O | . | X ] -> O plays 2: [ X | O | O | X ] ({1,2} -> O WINS!)
            +-- O plays 2: [ X | . | O | . ]
            |     +-- X plays 1: [ X | X | O | . ] ({0,1} -> X WINS on turn 3, stop immediately!)
            |     +-- X plays 3: [ X | . | O | X ] -> O plays 1: [ X | O | O | X ] ({1,2} -> O WINS!)
            +-- O plays 3: [ X | . | . | O ]
                  +-- X plays 1: [ X | X | . | O ] ({0,1} -> X WINS on turn 3, stop immediately!)
                  +-- X plays 2: [ X | . | X | O ] -> O plays 1: [ X | O | X | O ] (full -> DRAW)
    Opening at 0 gives (2, 2, 2); across all 4 openings (0, 1, 2, 3) totals are (12, 4, 8).
    
    def _play(
        board: List[int],
        depth: int,
        n_cells: int,
        through: List[List[int]],
        totals: List[int],
    ) -> None:
        # board = [x_mask, o_mask]; totals = [x_wins, o_wins, draws].
        # Even depth (0, 2, 4, ...) is X's turn (player 0); odd depth is O's turn (player 1).
        player = depth % 2
        occupied = board[0] | board[1]
    
        for cell in range(n_cells):
            cell_bit = 1 << cell
            if (occupied & cell_bit) != 0:
                continue
    
            # 1. Make the move on `cell`.
            board[player] |= cell_bit
    
            # 2. Check terminal conditions. Check win BEFORE full-board draw because a winning move
            #    on the very last empty cell is still a win, and the game stops immediately on any win.
            if is_win(board[player], through[cell]):
                totals[player] += 1
            elif depth + 1 == n_cells:
                totals[2] += 1
            else:
                _play(board, depth + 1, n_cells, through, totals)
    
            # 3. Undo the move (backtrack): flip `cell_bit` back from 1 to 0 for the next branch.
            board[player] ^= cell_bit
    
    
    def count_games(rows: int = 4, cols: int = 4, k: int = 3) -> Tuple[int, int, int]:
        """(x_wins, o_wins, draws): numbers of distinct move sequences ending in each outcome.
    
        Visits every game one by one, so it is only practical for small boards.
        """
        totals = [0, 0, 0]
        through = lines_through_cells(rows, cols, k)
        _play([0, 0], 0, rows * cols, through, totals)
        return totals[0], totals[1], totals[2]
    
  5. Stream individual games lazily with a generator

    If an interviewer asks for the actual move sequences rather than just the count, never append every sequence into a Python list — on a 4 x 4 board there are over 1.28 trillion games, which would exhaust terabytes of RAM. Instead, use a Python generator (yield), which pauses execution at each terminal game, hands one (tuple(moves), outcome) pair to the caller, and resumes backtracking only when the caller asks for the next game. Memory stays O(N) (at most 16 integers on moves) regardless of how many trillions of games exist:

    def enumerate_games(rows: int = 3, cols: int = 3, k: int = 3) -> Iterator[Tuple[Tuple[int, ...], str]]:
        """Yield (moves, outcome) for every game, one at a time; outcome is "X", "O" or "draw"."""
        through = lines_through_cells(rows, cols, k)
        yield from _walk([0, 0], [], rows * cols, through)
    
    
    def _walk(
        board: List[int],
        moves: List[int],
        n_cells: int,
        through: List[List[int]],
    ) -> Iterator[Tuple[Tuple[int, ...], str]]:
        # `moves` tracks the current path of cell indices from root to the current board state.
        player = len(moves) % 2
        winner = "X" if player == 0 else "O"
        occupied = board[0] | board[1]
    
        for cell in range(n_cells):
            cell_bit = 1 << cell
            if (occupied & cell_bit) != 0:
                continue
    
            board[player] |= cell_bit
            moves.append(cell)
    
            if is_win(board[player], through[cell]):
                # Yield an immutable tuple snapshot because `moves` is mutated during backtracking.
                yield tuple(moves), winner
            elif len(moves) == n_cells:
                yield tuple(moves), "draw"
            else:
                yield from _walk(board, moves, n_cells, through)
    
            # Undo both the move list entry and the player's bitmask before trying the next cell.
            moves.pop()
            board[player] ^= cell_bit
    

    Notice tuple(moves): we must freeze a copy of moves when yielding, because the very next step moves.pop() mutates moves in place as backtracking continues. On the 1 x 4 strip (k = 2) from Example 1, the first three yielded sequences are ((0, 1, 2, 3), "draw"), ((0, 1, 3, 2), "O"), and ((0, 2, 1), "X") (where play stops after 3 turns as soon as X covers {0, 1}).

  6. Measure the game tree and see why plain recursion is slow on 4x4

    On a board with N = rows * cols cells, the first move has N choices, the second has N - 1, and depth d has at most N! / (N - d)! nodes. Summing over all depths d = 0 .. N:

    Total nodes <= N! * (1/N! + 1/(N-1)! + ... + 1/1! + 1/0!) < e * N!   (where e ≈ 2.718)
    

    At each non-terminal node we loop over N cells and check at most L lines through the chosen cell, giving worst-case time O(N * L * N!) and stack space O(N). Early wins prune a large fraction of branches, yet 4 x 4 still has over 2 trillion tree nodes:

    Board   Game-tree nodes          Complete games (leaves)   Upper bound (sum N!/(N-d)!)
    3 x 3   549,946                  255,168                   986,410
    4 x 4   2,031,207,626,081        1,281,016,086,768         56,874,039,553,217 (~5.7e13)
    

    At 1,000,000 nodes per second in pure Python, visiting 2.03 * 10^12 nodes one by one would take over 23 days! Plain backtracking is great for streaming or small boards, so let's see how to make 4 x 4 counting finish in seconds.

  7. Speed up counting with memoization over board states

    Consider two different 4-move openings on 4 x 4: - Path A: X plays 0, O plays 3, X plays 5, O plays 15. - Path B: X plays 5, O plays 15, X plays 0, O plays 3.

    Both paths arrive at the exact same board state (x_mask, o_mask) with X on {0, 5} and O on {3, 15}, neither player has won yet, and it is X's turn next. Every valid sequence of remaining moves from Path A is also a valid sequence of remaining moves from Path B!

    Memoization means caching a function's output keyed by its essential state (x_mask, o_mask) so we compute the continuation counts (x_wins, o_wins, draws) from each reachable non-terminal board only once:

    Path A (X:0, O:3, X:5, O:15) ---\
                                     +---> state (x_mask, o_mask) ---> [compute subtree ONCE]
    Path B (X:5, O:15, X:0, O:3) ---/       returns (sub_x, sub_o, sub_draws) to BOTH callers!
    

    Crucially, this still counts ordered move sequences, not unique final boards: Path A adds (sub_x, sub_o, sub_draws) to its running total, and Path B also adds (sub_x, sub_o, sub_draws) to its running total, without re-exploring the subtree. On 4 x 4 (k = 3), the 2.03 * 10^12 tree nodes collapse into just 3,463,541 distinct non-terminal board states, finishing in ~12 seconds in CPython:

    def _count_from(
        x_mask: int,
        o_mask: int,
        depth: int,
        n_cells: int,
        through: List[List[int]],
        memo: Dict[Tuple[int, int], Tuple[int, int, int]],
    ) -> Tuple[int, int, int]:
        """Outcome counts of all ordered game continuations from non-terminal state (x_mask, o_mask)."""
        # memo maps (x_mask, o_mask) -> (x_wins, o_wins, draws) for all valid continuations.
        # `depth` does not need to be in the key because depth equals popcount(x_mask | o_mask).
        state_key = (x_mask, o_mask)
        if state_key in memo:
            return memo[state_key]
    
        x_wins = 0
        o_wins = 0
        draws = 0
        x_to_move = (depth % 2 == 0)
        occupied = x_mask | o_mask
    
        for cell in range(n_cells):
            cell_bit = 1 << cell
            if (occupied & cell_bit) != 0:
                continue
    
            if x_to_move:
                next_x = x_mask | cell_bit
                next_o = o_mask
                won = is_win(next_x, through[cell])
            else:
                next_x = x_mask
                next_o = o_mask | cell_bit
                won = is_win(next_o, through[cell])
    
            if won and x_to_move:
                x_wins += 1
            elif won:
                o_wins += 1
            elif depth + 1 == n_cells:
                draws += 1
            else:
                sub_x, sub_o, sub_draws = _count_from(
                    next_x, next_o, depth + 1, n_cells, through, memo
                )
                x_wins += sub_x
                o_wins += sub_o
                draws += sub_draws
    
        memo[state_key] = (x_wins, o_wins, draws)
        return memo[state_key]
    
    
    def count_games_memo(rows: int = 4, cols: int = 4, k: int = 3) -> Tuple[int, int, int]:
        """Same result as count_games, but each reachable board state is expanded only once."""
        memo: Dict[Tuple[int, int], Tuple[int, int, int]] = {}
        through = lines_through_cells(rows, cols, k)
        return _count_from(0, 0, 0, rows * cols, through, memo)
    

    Running count_games_memo(4, 4, 3) gives the exact 4 x 4 three-in-a-row breakdown:

    X wins:    711,350,838,432   (55.5%)
    O wins:    540,402,605,136   (42.2%)
    Draws:      29,262,643,200   ( 2.3%)
    ------------------------------------
    Total:   1,281,016,086,768   valid ordered games
    

    We can even verify the draw count independently: a drawn final board has 8 Xs, 8 Os, and zero length-3 lines, meaning no earlier move could have won either. Out of C(16, 8) = 12,870 ways to place 8 Xs and 8 Os, exactly 18 boards avoid all 24 lines, and each can be played in 8! * 8! = 40,320 * 40,320 = 1,625,702,400 move orders: 18 * 1,625,702,400 = 29,262,643,200 draws!

  8. Complete solution

    from typing import Dict, Iterator, List, Tuple
    
    # Cell (r, c) is mapped to bit index (r * cols + c) of an integer bitmask.
    # Each winning line only needs to step forward in 4 directions so we never count a line twice:
    # right (0, 1), down (1, 0), down-right (1, 1), and down-left (1, -1).
    DIRECTIONS = [(0, 1), (1, 0), (1, 1), (1, -1)]
    
    
    def winning_lines(rows: int, cols: int, k: int) -> List[int]:
        """Bitmask of every run of k consecutive cells: horizontal, vertical, both diagonals."""
        if k <= 0:
            return []
        # When k == 1, a single cell is already a full line; using 1 direction avoids 4x duplicates.
        directions = [(0, 1)] if k == 1 else DIRECTIONS
        lines: List[int] = []
        for r in range(rows):
            for c in range(cols):
                for dr, dc in directions:
                    # Check whether the k-th cell from (r, c) still lands inside the board.
                    last_r = r + (k - 1) * dr
                    last_c = c + (k - 1) * dc
                    if 0 <= last_r < rows and 0 <= last_c < cols:
                        mask = 0
                        for step in range(k):
                            cell_index = (r + step * dr) * cols + (c + step * dc)
                            mask |= 1 << cell_index
                        lines.append(mask)
        return lines
    
    
    def lines_through_cells(rows: int, cols: int, k: int) -> List[List[int]]:
        """For each cell, the winning lines that contain it."""
        all_lines = winning_lines(rows, cols, k)
        # through[cell] holds the list of line bitmasks that include `cell`, e.g. [0b111, 0b1001001, ...].
        through: List[List[int]] = []
        for cell in range(rows * cols):
            cell_bit = 1 << cell
            containing_lines: List[int] = []
            for line in all_lines:
                if (line & cell_bit) != 0:
                    containing_lines.append(line)
            through.append(containing_lines)
        return through
    
    
    def is_win(marks: int, lines: List[int]) -> bool:
        """True if `marks` covers all cells of at least one bitmask in `lines`."""
        for line in lines:
            # (marks & line) == line holds iff every 1-bit in `line` is also 1 in `marks`.
            if (marks & line) == line:
                return True
        return False
    
    
    # ---- Plain recursion and backtracking ----------------------------------------------------
    
    def _play(
        board: List[int],
        depth: int,
        n_cells: int,
        through: List[List[int]],
        totals: List[int],
    ) -> None:
        # board = [x_mask, o_mask]; totals = [x_wins, o_wins, draws].
        # Even depth (0, 2, 4, ...) is X's turn (player 0); odd depth is O's turn (player 1).
        player = depth % 2
        occupied = board[0] | board[1]
    
        for cell in range(n_cells):
            cell_bit = 1 << cell
            if (occupied & cell_bit) != 0:
                continue
    
            # 1. Make the move on `cell`.
            board[player] |= cell_bit
    
            # 2. Check terminal conditions. Check win BEFORE full-board draw because a winning move
            #    on the very last empty cell is still a win, and the game stops immediately on any win.
            if is_win(board[player], through[cell]):
                totals[player] += 1
            elif depth + 1 == n_cells:
                totals[2] += 1
            else:
                _play(board, depth + 1, n_cells, through, totals)
    
            # 3. Undo the move (backtrack): flip `cell_bit` back from 1 to 0 for the next branch.
            board[player] ^= cell_bit
    
    
    def count_games(rows: int = 4, cols: int = 4, k: int = 3) -> Tuple[int, int, int]:
        """(x_wins, o_wins, draws): numbers of distinct move sequences ending in each outcome.
    
        Visits every game one by one, so it is only practical for small boards.
        """
        totals = [0, 0, 0]
        through = lines_through_cells(rows, cols, k)
        _play([0, 0], 0, rows * cols, through, totals)
        return totals[0], totals[1], totals[2]
    
    
    def enumerate_games(rows: int = 3, cols: int = 3, k: int = 3) -> Iterator[Tuple[Tuple[int, ...], str]]:
        """Yield (moves, outcome) for every game, one at a time; outcome is "X", "O" or "draw"."""
        through = lines_through_cells(rows, cols, k)
        yield from _walk([0, 0], [], rows * cols, through)
    
    
    def _walk(
        board: List[int],
        moves: List[int],
        n_cells: int,
        through: List[List[int]],
    ) -> Iterator[Tuple[Tuple[int, ...], str]]:
        # `moves` tracks the current path of cell indices from root to the current board state.
        player = len(moves) % 2
        winner = "X" if player == 0 else "O"
        occupied = board[0] | board[1]
    
        for cell in range(n_cells):
            cell_bit = 1 << cell
            if (occupied & cell_bit) != 0:
                continue
    
            board[player] |= cell_bit
            moves.append(cell)
    
            if is_win(board[player], through[cell]):
                # Yield an immutable tuple snapshot because `moves` is mutated during backtracking.
                yield tuple(moves), winner
            elif len(moves) == n_cells:
                yield tuple(moves), "draw"
            else:
                yield from _walk(board, moves, n_cells, through)
    
            # Undo both the move list entry and the player's bitmask before trying the next cell.
            moves.pop()
            board[player] ^= cell_bit
    
    
    # ---- Memoized count: same sequence totals, one expansion per board state -----------------
    
    def _count_from(
        x_mask: int,
        o_mask: int,
        depth: int,
        n_cells: int,
        through: List[List[int]],
        memo: Dict[Tuple[int, int], Tuple[int, int, int]],
    ) -> Tuple[int, int, int]:
        """Outcome counts of all ordered game continuations from non-terminal state (x_mask, o_mask)."""
        # memo maps (x_mask, o_mask) -> (x_wins, o_wins, draws) for all valid continuations.
        # `depth` does not need to be in the key because depth equals popcount(x_mask | o_mask).
        state_key = (x_mask, o_mask)
        if state_key in memo:
            return memo[state_key]
    
        x_wins = 0
        o_wins = 0
        draws = 0
        x_to_move = (depth % 2 == 0)
        occupied = x_mask | o_mask
    
        for cell in range(n_cells):
            cell_bit = 1 << cell
            if (occupied & cell_bit) != 0:
                continue
    
            if x_to_move:
                next_x = x_mask | cell_bit
                next_o = o_mask
                won = is_win(next_x, through[cell])
            else:
                next_x = x_mask
                next_o = o_mask | cell_bit
                won = is_win(next_o, through[cell])
    
            if won and x_to_move:
                x_wins += 1
            elif won:
                o_wins += 1
            elif depth + 1 == n_cells:
                draws += 1
            else:
                sub_x, sub_o, sub_draws = _count_from(
                    next_x, next_o, depth + 1, n_cells, through, memo
                )
                x_wins += sub_x
                o_wins += sub_o
                draws += sub_draws
    
        memo[state_key] = (x_wins, o_wins, draws)
        return memo[state_key]
    
    
    def count_games_memo(rows: int = 4, cols: int = 4, k: int = 3) -> Tuple[int, int, int]:
        """Same result as count_games, but each reachable board state is expanded only once."""
        memo: Dict[Tuple[int, int], Tuple[int, int, int]] = {}
        through = lines_through_cells(rows, cols, k)
        return _count_from(0, 0, 0, rows * cols, through, memo)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of enumerating every valid Tic-Tac-Toe game like mapping out every possible ending in a choose-your-own-adventure book using a single erasable chalkboard. At each turn — called a ply, meaning one single move by one player — you pick an empty square, draw X or O in chalk, and check whether the story just ended in a win or a full board; if not, you turn to the next page and repeat, and as soon as you finish exploring all endings from that choice, you erase that single chalk mark so the board is clean for the next empty square. This "place, explore, erase" loop is called backtracking, a recursive technique that explores an entire decision tree using only one board in memory.

A naive approach that generates all 16! permutations of the 16 squares fails in two ways: it keeps placing marks after someone has already won (overcounting sequences no real game could ever reach), and scanning a 2D list of lists after every move wastes time re-checking squares untouched by the latest move. Even with early stopping, plain recursion visits over 2 trillion tree nodes on a 4 x 4 board because different move orders reach the exact same mid-game board and re-solve its future from scratch. We make each step fast using a bitmask — an integer whose binary 0/1 bits represent which squares a player owns — and we make full-board counting fast using memoization, which caches the continuation counts (x_wins, o_wins, draws) for each reachable board state (x_mask, o_mask) so identical mid-game positions are solved once instead of millions of times.

Let's trace the opening branch of the 1 x 4 strip ([0, 1, 2, 3]) with k = 2 from Example 1, where the winning line masks are {0, 1} (3), {1, 2} (6), and {2, 3} (12): 1. X opens at 0 and O replies at 1 ([X, O, ., .]): X playing 2 forces O onto 3 ([X, O, X, O] -> 1 draw), while X playing 3 lets O take 2 and complete {1, 2} ([X, O, O, X] -> 1 O win). 2. Backtracking erases O at 1 and tries O at 2 ([X, ., O, .]): when X takes 1, X completes {0, 1} on turn 3 ([X, X, O, .] -> 1 X win, stopping without filling square 3); when X takes 3, O takes 1 ([X, O, O, X] -> 1 O win). 3. Trying O at 3 gives 1 X win (0 -> 3 -> 1) and 1 draw (0 -> 3 -> 2 -> 1), so X at 0 yields (2, 2, 2), and summing across all four openings (0, 1, 2, 3) produces (12, 4, 8).

Complexity

Let N = rows * cols (16 cells on 4 x 4) and L be the maximum number of length-k winning lines passing through a single cell (L = 7 for a center cell on 4 x 4 with k = 3).

  • Plain backtracking (count_games, enumerate_games):
    • Time — O(N * L * N!) in the worst case: Depth d has at most N! / (N - d)! nodes, so the entire game tree has fewer than e * N! nodes (e ≈ 2.718), and at each non-terminal node we loop over N cells and check at most L precomputed line bitmasks in O(1) bitwise operations each. Early wins prune heavily — 4 x 4 with k = 3 visits 2,031,207,626,081 tree nodes rather than 5.7 * 10^13, though visiting 2 trillion nodes one by one still takes hours or days in Python.
    • Space — O(N): Recursion goes at most N plies deep, mutating a two-integer board in place, and enumerate_games uses a generator (a function that yields one item at a time on demand rather than building a list in memory) so RAM usage stays O(N).
  • Memoized counting (count_games_memo):
    • Time — O(P * N * L) where P is the number of reachable non-terminal board positions: Each unique (x_mask, o_mask) pair is expanded once by looping over N cells and testing up to L lines, and every subsequent path reaching that board does an O(1) dictionary lookup. Because each cell is empty, X, or O, P <= 3^N (43,046,721 for N = 16), and in practice P = 3,463,541 on 4 x 4 with k = 3.
    • Space — O(P): The memo dictionary stores one (x_wins, o_wins, draws) tuple for each of the P reachable non-terminal positions, plus O(N) call-stack depth.

Edge cases

  • Winning on the very last empty cell: When the 16th move fills the board and completes 3-in-a-row, it is an O win (or X win on odd-sized boards), not a draw — always test is_win before testing depth + 1 == n_cells.
  • Completing two lines with a single move: Placing a mark at the intersection of a horizontal line and a diagonal line ends the game once and increments the winner's count by 1, not 2, because is_win returns True immediately on the first matched line.
  • Boards where k cannot fit (k > rows and k > cols, e.g., 2 x 2 with k = 3): winning_lines is empty, nobody can ever win, and all N! move orders (24 on 2 x 2) end in draws.
  • Single-cell win (k = 1): Every single cell is already a complete line; X wins immediately on move 1 across all N opening choices ((N, 0, 0)), and guarding k == 1 in winning_lines prevents adding the same 1-cell line four times across the four directions.
  • One-dimensional strips (1 x 3 or 1 x 4 with k = 3): On 1 x 3, X only gets two turns (ceil(3 / 2) = 2 marks), and on 1 x 4, X gets only two turns (4 / 2 = 2 marks), so neither player can ever place 3 marks and every game ends in a draw.

Common mistakes

  • Continuing recursion after a win: Failing to stop the branch immediately when is_win returns True keeps filling empty squares after the game is already over, inflating counts with illegal sequences.
  • Forgetting or botching the undo step: Using |= instead of ^= (or & ~cell_bit) when backtracking leaves marks permanently stuck on board, corrupting every sibling branch in the loop.
  • Yielding the live moves list instead of tuple(moves): Because _walk calls moves.append(...) and moves.pop() on a single list, yielding moves directly hands the caller a list that mutates and eventually empties out.
  • Missing short diagonals or shifted length-3 windows: Checking only the two length-4 corner-to-corner diagonals or only full 4-cell rows gives 10 lines instead of 24 — remember that a length-4 row has two length-3 windows (0..2 and 1..3) and off-main diagonals like (0, 1)-(1, 2)-(2, 3) also have 3 cells.
  • Confusing sequence counts with unique terminal boards (or random-play probabilities): Memoizing (x_mask, o_mask) still counts ordered sequences (1.28 * 10^12), which is ~500,000x larger than the number of unique terminal boards (2,572,460); also, dividing x_wins by total sequences is not X's win probability under random play, because a 5-move game has far higher probability (1/16)*(1/15)*(1/14)*(1/13)*(1/12) than a 16-move game (1/16!).

Follow-up questions

  • What independent reference checks can confirm that your game counter has no off-by-one or overcounting bugs? First, run the exact same parameterized functions on classic 3 x 3 (k = 3) and verify against the published combinatorial totals: 255,168 total games (131,184 X wins, 77,904 O wins, 46,080 draws). Second, cross-check small grids (1 x 3 through 2 x 3 with k = 2, 3) against a dead-simple brute force that loops over itertools.permutations(range(N)) and truncates each permutation at the first win, and check count_games against count_games_memo on 8- and 9-cell grids. Finally, verify the 4 x 4 draw total algebraically: out of C(16, 8) = 12,870 full boards with 8 Xs and 8 Os, exactly 18 have no 3-in-a-row, so there must be 18 * 8! * 8! = 29,262,643,200 drawn sequences.
  • When you report wins for X, wins for O, and draws separately, how should those three totals compare and why? Maintain three counters (x_wins, o_wins, draws), incrementing the active mover's counter (depth % 2) when is_win triggers and draws when depth + 1 == n_cells without a win. On 4 x 4 (k = 3), X wins 711,350,838,432 games (55.5%), O wins 540,402,605,136 (42.2%), and draws are just 29,262,643,200 (2.3%). X naturally leads because X moves first, always holds at least as many marks as O, gets the first chance to win on move 5 (versus move 6 for O), and draws are tiny because avoiding all 24 length-3 lines across 16 squares is very hard.
  • Pure recursive search over all 4x4 play-throughs takes far too long in Python—which algorithmic and systems optimizations make exact counting practical? For counting, bitmasks plus memoization on (x_mask, o_mask) is the biggest win by far, shrinking 2.03 * 10^12 tree nodes down to 3,463,541 states (~12 seconds in CPython, or < 50 ms in C++/Rust). If you cannot memoize (for example, if streaming or inspecting every sequence), exploit the 8 symmetries of the square so the 16 opening moves collapse into just 3 equivalence classes — 4 corners, 8 edge cells, and 4 center cells — cutting work by ~5.4x via 4 * count(corner) + 8 * count(edge) + 4 * count(center). From there, fan out the independent depth-1 or depth-2 subtrees across CPU cores and implement the tight bitmask loop in C++ or Rust, where bitwise operations run in registers at hundreds of millions of nodes per second.
  • Suppose we want the number of unique final board layouts rather than ordered move histories—how would you modify the search, both with and without rotational/reflectional equivalence? Instead of summing sequence counts across paths, perform a graph search (DFS/BFS) with a visited set of (x_mask, o_mask) pairs so each reachable board is visited once, and insert every winning or drawn board into a terminal_boards set — on 4 x 4 (k = 3), this yields 2,572,460 distinct terminal boards (1,522,416 X wins, 1,050,026 O wins, 18 draws). To deduplicate rotations and reflections, map each terminal board to its canonical form — a single standard representative chosen by generating all 8 rotated/reflected (x_mask, o_mask) pairs and taking their minimum tuple — and store those canonical tuples in a set, which collapses the 2,572,460 boards into 322,182 symmetry-unique terminal boards (190,623 X wins, 131,555 O wins, 4 draws).

Follow-up questions

Similar questions

More Decagon interview questions

All 20 Decagon questions →