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:
- 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).
- 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 (1win 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 row1(O, O, O) immediately (1win for'O', cutting off the remaining three empty cells). - Playing
(0, 2)blocks'X''s top-row threat and yields4'O'wins and2draws across'X''s three replies. - Playing
(2, 0)yields2'X'wins and3'O'wins. - Playing
(2, 1)yields2'X'wins,1'O'win, and2draws.
Summing across all four opening choices gives {'X': 4, 'O': 9, 'Draw': 4, 'Total': 17}.
Constraints
boardis eitherNoneor a3 x 3list of lists whose elements belong to{'X', 'O', '.'}.- Every provided
boardis a valid, non-terminal position (neither side already has three in a line, and at least one'.'cell remains). turnis'X'or'O'.- Calling
count_tic_tac_toe_games()from the blank grid must finish within2.0seconds.
Step-by-step walkthrough
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:
- Move order matters:
Xat(0,0),Oat(1,1),Xat(0,1)is a different game sequence fromXat(0,1),Oat(1,1),Xat(0,0), even though both sequences produce the exact same board after move 3. - 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 .withXto move), playing(2,2)completes the main diagonal right away, so the remaining two open squares are never filled—collapsing those2permutations into1finished game and givingTotal = 5rather than3! = 6.
- Move order matters:
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,168legal games (549,945total moves). However, it repeats the same work many times because different opening orders keep landing on the exact same mid-game board.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 fromXX. / .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 dictionarymemothe 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,520reachable non-terminal boards is solved only once.
- 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
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 indices0..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 | 8Because the board before a move had no winner, a newly completed 3-in-a-row must pass through the square
moved_cellthat was just played. PrecomputingLINES_BY_CELL[moved_cell]letscompletes_winning_linecheck only the 2, 3, or 4 lines touchingmoved_cellinstead 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 FalseWrite the memoized backtracking search and public wrapper
In
count_from_state, we keymemoby"".join(cells) + current_turn. For each empty cell, we placecurrent_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 resetcells[cell_idx] = "."afterward.In
count_tic_tac_toe_games, we copy the input 2Dboardinto a freshcellslist 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, }Trace Example 1 as a complete game tree
Let's trace Example 1 (
X . O / O X . / X O ., withXto 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, andTotal: 5.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)):
Xplays(2, 2): Completes main diagonalX, X, Xand stops immediately ->1game (X).Xplays(0, 1): Game continues;Ocan play(1, 2)(lettingXtake(2, 2)to win on move 9 ->X) or(2, 2)(forcingXat(1, 2)with no line ->Draw) ->2games (1 X, 1 Draw).Xplays(1, 2): Symmetric to(0, 1):Oat(0, 1)letsXwin at(2, 2)(X), whileOat(2, 2)leavesXat(0, 1)for aDraw->2games (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 most4,520 * 9 * 4elementary checks on an empty 3x3 board). Each reachable non-terminal state is expanded at most once before being stored inmemo; 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)formemoplusO(9)call-stack depth.memostores one 3-entry dictionary for each of thePreachable non-terminal states, while the in-placecellslist and recursion stack never exceed depth 9 (one frame per empty square).
Edge cases
board=Nonedefault: Initializescellsto nine"."entries and starts fromturn("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—either1win forturnif that final square completes a line, or1Drawotherwise. - Immediate win with empty squares still left: As soon as
completes_winning_linereturnsTrue, the branch adds1tocounts[current_turn]and does not recurse on the remaining"."squares. - Caller's
boardimmutability: Copyingboardinto a fresh flatcellslist ensures backtracking never leaves temporary marks in, or mutates, the caller's 2D list. - Custom starting
turn: Includingcurrent_turninstate_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 thekempty squares ignores early game termination (for example, inflating Example 1's 5 legal trajectories into 6). - Using a
visitedset 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,792games where"X"wins on the 9th and final move as draws. - Forgetting to undo
cells[cell_idx] = "."on terminal branches: Usingreturnorcontinueafter a win without restoring"."corrupts the board for sibling moves in the loop. - Mutating a cached dictionary inside
memo: Oncememo[state_key] = countsis saved, parent calls must copy/add values into their own freshcountsdictionary rather than modifyingchild_countsin 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
visitedset of(board_string, turn)states plus aterminal_boardsset is the exact right tool: skip any state already invisitedso identical mid-game boards are never explored twice, and whenever a move wins or fills the board, add the resulting 9-character board string toterminal_boards[outcome]. Because sets automatically deduplicate boards reached through different move orders, starting from an empty 3x3 board yields958distinct final boards (626won byX,316won byO, and16draws). - 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 (
0to511), using one integerx_maskfor"X"and oneo_maskfor"O". Finding empty squares isfree = 0b111111111 & ~(x_mask | o_mask), picking and clearing the lowest empty square uses the bitwise trickbit = free & -free; free ^= bit, applying a move isnew_mask = me | bit(requiring zero undo cleanup because integers are immutable), checking a win tests(new_mask & line_mask) == line_maskagainst 8 integer constants like0b000000111, and(x_mask, o_mask)serves directly as a fast integer-tuplememokey 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 theb_dlegal moves at each depthduntil a win or draw occurs, and records the productW = b_0 * b_1 * ... * b_{L-1}. By probability, the expected value ofWacross random playouts equals the exact total number of terminal game sequences (and attributingWto 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
- What changes if we want the number of unique ending grid layouts instead of ordered play histories?
- How could integer bitmasks replace the list-based grid to accelerate move updates and three-in-a-row checks?
- 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?
Similar questions
- Exclusive Function Runtime
- Constant-Time Tic-Tac-Toe Board
- Rolling Score Tracker for Active Sessions
- Game-Tree Enumeration for 4x4 Three-in-a-Row
- Rolling-Window CSAT Score Tracker
- Exclusive Handler Timing from Session Logs
More Decagon interview questions
- Game-Tree Enumeration for 4x4 Three-in-a-Row Medium
- 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