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 ofkmatching 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 a4 x 4grid withk = 3, three consecutive marks suffice (a 4-square row or column contains two overlapping 3-square windows), and a single move completing twok-square windows at once still counts as one win. - Full-grid draw (
"draw"): Every square (rows * colsturns) is filled without either player ever completingkconsecutive marks. If the very last unoccupied square completeskconsecutive 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 contiguousk-square line (horizontal, vertical, and both diagonal directions), where squareicorresponds to bit1 << i. Return[]ifk <= 0or nok-square line fits on the grid.lines_through_cells(rows: int, cols: int, k: int) -> List[List[int]]: Return a list of lengthrows * colswhosei-th entry contains all bitmasks fromwinning_lines(rows, cols, k)that pass through squarei.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]]: Lazilyyield(moves, outcome)one game at a time (as a generator, without building a list in memory), trying available squares in ascending index order0, 1, ..., rows * cols - 1, whereoutcomeis"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 ascount_games, caching continuation counts per non-terminal board state so3 x 3and4 x 4grids 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 <= 4androws * cols <= 16.0 <= k <= 5(ifk <= 0ork > max(rows, cols), no winning lines exist).count_gamesis evaluated on small grids (rows * cols <= 9), whereascount_games_memomust handle up to4 x 4(16squares).enumerate_gamesmust return a lazy iterator/generator (do not materialize all games in memory at once) and visit candidate squares in strictly increasing index order0 .. rows * cols - 1.
Step-by-step walkthrough
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 colsboard withk-in-a-row costs zero extra complexity and lets us verify our code on tiny boards (like1 x 3or3 x 3) where we know the exact answer by hand.Number the cells and represent the board with bitmasks
A bitmask is an ordinary integer whose binary digits (
0or1) act as tiny on/off switches — one switch per cell on the board. Numbering the 16 cells of a4 x 4board row by row gives each(r, c)coordinate the single indexr * 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 bitiset to1whenever X occupies celli) ando_mask(with bitiset to1whenever O occupies celli). Thenx_mask | o_maskhas bitiset whenever celliis 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 a4 x 4board withk = 3, this produces8horizontal +8vertical +4down-right +4down-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 linesCheck 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 throughcell. 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
markscovers alinebitmask takes one bitwise AND:(marks & line) == line. Bitwise&keeps only the bits that are1in both integers, so the result equalslineif and only if the player holds allkcells 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 FalseExplore 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; atdepth = 1, O makes the 2nd move; in general,player = depth % 2(0for X on even depths,1for 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 tototals[player]and stop (do not recurse further); else ifdepth + 1 == n_cells, add 1 tototals[2](a draw); else recurse todepth + 1. 3. Undo the move: flip that exact bit back off withboard[player] ^= cell_bitso the board returns to its exact previous state before the loop tries the next empty cell.Here is the opening branch (
Xstarts at square0) on the Example 11 x 4strip withk = 2(squares0, 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]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 a4 x 4board 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 staysO(N)(at most 16 integers onmoves) 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_bitNotice
tuple(moves): we must freeze a copy ofmoveswhen yielding, because the very next stepmoves.pop()mutatesmovesin place as backtracking continues. On the1 x 4strip (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 asXcovers{0, 1}).Measure the game tree and see why plain recursion is slow on 4x4
On a board with
N = rows * colscells, the first move hasNchoices, the second hasN - 1, and depthdhas at mostN! / (N - d)!nodes. Summing over all depthsd = 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
Ncells and check at mostLlines through the chosen cell, giving worst-case timeO(N * L * N!)and stack spaceO(N). Early wins prune a large fraction of branches, yet4 x 4still 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^12nodes one by one would take over 23 days! Plain backtracking is great for streaming or small boards, so let's see how to make4 x 4counting finish in seconds.Speed up counting with memoization over board states
Consider two different 4-move openings on
4 x 4: - Path A: X plays0, O plays3, X plays5, O plays15. - Path B: X plays5, O plays15, X plays0, O plays3.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. On4 x 4(k = 3), the2.03 * 10^12tree 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 exact4 x 4three-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 gamesWe 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,870ways to place 8 Xs and 8 Os, exactly18boards avoid all 24 lines, and each can be played in8! * 8! = 40,320 * 40,320 = 1,625,702,400move orders:18 * 1,625,702,400 = 29,262,643,200draws!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: Depthdhas at mostN! / (N - d)!nodes, so the entire game tree has fewer thane * N!nodes (e ≈ 2.718), and at each non-terminal node we loop overNcells and check at mostLprecomputed line bitmasks inO(1)bitwise operations each. Early wins prune heavily —4 x 4withk = 3visits2,031,207,626,081tree nodes rather than5.7 * 10^13, though visiting 2 trillion nodes one by one still takes hours or days in Python. - Space —
O(N): Recursion goes at mostNplies deep, mutating a two-integer board in place, andenumerate_gamesuses a generator (a function thatyields one item at a time on demand rather than building a list in memory) so RAM usage staysO(N).
- Time —
- Memoized counting (
count_games_memo):- Time —
O(P * N * L)wherePis the number of reachable non-terminal board positions: Each unique(x_mask, o_mask)pair is expanded once by looping overNcells and testing up toLlines, and every subsequent path reaching that board does anO(1)dictionary lookup. Because each cell is empty,X, orO,P <= 3^N(43,046,721forN = 16), and in practiceP = 3,463,541on4 x 4withk = 3. - Space —
O(P): Thememodictionary stores one(x_wins, o_wins, draws)tuple for each of thePreachable non-terminal positions, plusO(N)call-stack depth.
- Time —
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
Owin (orXwin on odd-sized boards), not a draw — always testis_winbefore testingdepth + 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, not2, becauseis_winreturnsTrueimmediately on the first matched line. - Boards where
kcannot fit (k > rowsandk > cols, e.g.,2 x 2withk = 3):winning_linesis empty, nobody can ever win, and allN!move orders (24on2 x 2) end in draws. - Single-cell win (
k = 1): Every single cell is already a complete line;Xwins immediately on move 1 across allNopening choices ((N, 0, 0)), and guardingk == 1inwinning_linesprevents adding the same 1-cell line four times across the four directions. - One-dimensional strips (
1 x 3or1 x 4withk = 3): On1 x 3,Xonly gets two turns (ceil(3 / 2) = 2marks), and on1 x 4,Xgets only two turns (4 / 2 = 2marks), 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_winreturnsTruekeeps 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 onboard, corrupting every sibling branch in the loop. - Yielding the live
moveslist instead oftuple(moves): Because_walkcallsmoves.append(...)andmoves.pop()on a single list, yieldingmovesdirectly 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..2and1..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, dividingx_winsby 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,168total games (131,184X wins,77,904O wins,46,080draws). Second, cross-check small grids (1 x 3through2 x 3withk = 2, 3) against a dead-simple brute force that loops overitertools.permutations(range(N))and truncates each permutation at the first win, and checkcount_gamesagainstcount_games_memoon 8- and 9-cell grids. Finally, verify the4 x 4draw total algebraically: out ofC(16, 8) = 12,870full boards with 8 Xs and 8 Os, exactly18have no 3-in-a-row, so there must be18 * 8! * 8! = 29,262,643,200drawn sequences. - When you report wins for
X, wins forO, 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) whenis_wintriggers anddrawswhendepth + 1 == n_cellswithout a win. On4 x 4(k = 3),Xwins711,350,838,432games (55.5%),Owins540,402,605,136(42.2%), and draws are just29,262,643,200(2.3%).Xnaturally leads becauseXmoves first, always holds at least as many marks asO, gets the first chance to win on move 5 (versus move 6 forO), 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, shrinking2.03 * 10^12tree nodes down to3,463,541states (~12 seconds in CPython, or< 50 msin 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 via4 * 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
visitedset of(x_mask, o_mask)pairs so each reachable board is visited once, and insert every winning or drawn board into aterminal_boardsset — on4 x 4(k = 3), this yields2,572,460distinct terminal boards (1,522,416X wins,1,050,026O wins,18draws). 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 the2,572,460boards into322,182symmetry-unique terminal boards (190,623X wins,131,555O wins,4draws).
Follow-up questions
- What independent reference checks can confirm that your game counter has no off-by-one or overcounting bugs?
- When you report wins for `X`, wins for `O`, and draws separately, how should those three totals compare and why?
- Pure recursive search over all 4x4 play-throughs takes far too long in Python—which algorithmic and systems optimizations make exact counting practical?
- 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?
Similar questions
- Exclusive Function Runtime
- Enumerating Tic-Tac-Toe Move Sequences by Outcome
- Constant-Time Tic-Tac-Toe Board
- Rolling Score Tracker for Active Sessions
- Rolling-Window CSAT Score Tracker
- Exclusive Handler Timing from Session Logs
More Decagon interview questions
- Enumerating Tic-Tac-Toe Move Sequences by Outcome Hard
- Versioned Recipe Cart with Bulk Ingredient Pricing Hard
- Security Architecture for an External-Facing LLM Assistant Medium Pro
- Rolling-Window CSAT Score Tracker Easy Pro
- Cart State Management with Undo and Redo Medium Pro
- Optimal 3x3 Tic-Tac-Toe Solver via Backtracking Medium Pro
- Project Ownership, Lessons From a Setback, and Daily AI Judgment Medium Pro
- Transactional Shopping Cart with Nested Scopes Hard Pro
- Exclusive Function Runtime Medium Pro
- Batched Message Dispatcher with Individual Cooldown Retries Medium Pro