Problem Description
Given a 3x3 Tic-Tac-Toe board represented as a string array, determine if the board state is valid—that is, whether it is possible to reach such a state during the course of a valid Tic-Tac-Toe game. The board contains characters 'X', 'O', and ' ' (empty spaces). The game rules impose that the first player (X) always starts, players must alternate moves, and the game stops once one of the players wins (or when the board is full). This means the counts of X’s and O’s and any winning configuration must satisfy specific conditions.
Key Insights
- Count the occurrences of 'X' and 'O'. Valid states require that either countX == countO or countX == countO + 1.
- Check for winning configurations (three in a row) for both X and O.
- If X wins, then countX must equal countO + 1.
- If O wins, then countX must equal countO.
- Both players cannot win simultaneously.
- The board state must adhere to the turn order and termination conditions.
Space and Time Complexity
Time Complexity: O(1) - The board size is fixed (3x3), so iterations are constant. Space Complexity: O(1) - Only a few counters and helper functions are used regardless of input size.
Solution
We validate the board by:
- Counting 'X' and 'O' on the board.
- Verifying that X has either the same number of moves as O or one more move.
- Checking if there is a winning row, column, or diagonal for X or O.
- Ensuring that if one player wins, the counts correspond to the expected turn (if X wins, then countX must be one more than countO; if O wins, counts must be equal) and both winning simultaneously is invalid.
To implement this, we use helper functions to detect wins and straightforward counting. The use of fixed iterations (3 rows, 3 columns, 2 diagonals) ensures constant time, making the overall solution efficient.