FastPrepCount Complete Tic-Tac-Toe Games

Count Complete Tic-Tac-Toe Games

Decagon logoDecagon● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Given a legal partial 3 x 3 Tic-Tac-Toe board, count how many distinct complete legal games can extend it.

X moves first, the players alternate turns, and a game ends immediately when either player completes a row, column, or diagonal, or when the board becomes full. Different future move orders count as different games. If the supplied board is already terminal, its empty continuation counts as one complete game.

The board contains X, O, and . for an empty cell. It is guaranteed to be reachable from the empty board without any move after an earlier win. Only future moves after the supplied board are counted; histories that may have led to that board are not part of the result.

Function

countTicTacToeGames(board: String[]) → int

Examples

Example 1

board = ["...","...","..."]return = 255168

From the empty board, there are 255168 distinct legal move sequences when play stops at the first win or a full board.

Example 2

board = ["XX.","OO.","..."]return = 73

It is X's turn. Summing every legal continuation from the four empty cells gives 73.

Example 3

board = ["XXX","OO.","..."]return = 1

X has already won, so no further move is legal and the empty continuation contributes one complete game.

Constraints

  • board.length = 3 and board[r].length = 3.
  • Every cell is X, O, or ..
  • board is a legal reachable position: X moved first, turns alternated, and no move was played after a win.
  • The answer is at most 255168 and fits a signed 32-bit integer.

More Decagon problems

See Decagon hiring insights
public int countTicTacToeGames(String[] board) {
    // Write your code here.
}
board["...","...","..."]
expected255168
Checking account…