Valid Tic-Tac-Toe State - Problem

Given a Tic-Tac-Toe board as a string array board, return true if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.

The board is a 3 x 3 array that consists of characters ' ', 'X', and 'O'. The ' ' character represents an empty square.

Rules of Tic-Tac-Toe:

  • Players take turns placing characters into empty squares ' '
  • The first player always places 'X' characters, while the second player always places 'O' characters
  • 'X' and 'O' characters are always placed into empty squares, never filled ones
  • The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal
  • The game also ends if all squares are non-empty
  • No more moves can be played if the game is over

Input & Output

Example 1 — Valid Game State
$ Input: board = ["O ", " ", " "]
Output: false
💡 Note: O went first, but X should always go first. This violates the turn order rule.
Example 2 — Valid Game State
$ Input: board = ["XOX", " X ", " "]
Output: false
💡 Note: X has 3 moves and O has 1 move. Since X goes first, this means O should have made 2 moves. Invalid turn count.
Example 3 — Valid End State
$ Input: board = ["XXX", " ", "OOO"]
Output: false
💡 Note: Both X and O have winning lines, which is impossible in a valid game. Only one player can win.

Constraints

  • board.length == 3
  • board[i].length == 3
  • board[i][j] is either 'X', 'O', or ' '

Visualization

Tap to expand
Valid Tic-Tac-Toe State INPUT ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' board = [ "O ", " ", " "] Count: X=0, O=1 ALGORITHM STEPS 1 Count X and O X=0, O=1 2 Check Count Rule O count > X count? 1 > 0 = TRUE (INVALID!) 3 Valid Count Rules X = O or X = O + 1 (X always goes first) 4 Check Win States If X wins: X = O + 1 If O wins: X = O VALIDATION FAILED O cannot move before X O=1 > X=0 is impossible FINAL RESULT Output: false Invalid state: O moved first, but X always goes first! Key Insight: Single-pass validation checks: (1) X count must equal O count OR be one more (X always first) (2) Both players cannot win simultaneously (3) If X wins, X=O+1; if O wins, X=O This board fails rule 1: O=1 but X=0, meaning O moved before X which violates game rules. TutorialsPoint - Valid Tic-Tac-Toe State | Single-Pass Validation Approach
Asked in
Google 15 Amazon 12 Microsoft 10 Apple 8
28.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen