Valid Tic-Tac-Toe State - Problem
Imagine you're a referee for a tic-tac-toe tournament, and you need to determine if a given board state is legally reachable during a valid game.
You're given a 3ร3 tic-tac-toe board as a string array, where each cell contains either:
'X'- First player's move'O'- Second player's move' '- Empty square
Game Rules:
- Player X always goes first
- Players alternate turns (X, then O, then X, etc.)
- Players can only place marks in empty squares
- Game ends when someone gets 3 in a row (horizontally, vertically, or diagonally)
- Game also ends when the board is full
- No moves can be made after the game ends
Your task is to return true if this board state could have been reached during a valid game, or false if it's impossible.
Example: If X has already won but there are more O's placed after that winning move, the state is invalid!
Input & Output
example_1.py โ Valid Mid-Game State
$
Input:
["O ", " ", " "]
โบ
Output:
false
๐ก Note:
Invalid because O went first, but X should always go first in tic-tac-toe.
example_2.py โ Valid Win State
$
Input:
["XOX", " X ", " "]
โบ
Output:
false
๐ก Note:
Invalid because both players seem to have continued playing after X won the middle column.
example_3.py โ Valid Empty Start
$
Input:
["XXX", " ", "OOO"]
โบ
Output:
false
๐ก Note:
Invalid because both X and O have winning rows, which is impossible in a real game.
Visualization
Tap to expand
Understanding the Visualization
1
Count the Pieces
Count X's and O's to ensure X went first and players alternated properly
2
Find the Winners
Check all rows, columns, and diagonals for three-in-a-row
3
Validate End Conditions
Ensure the game stopped immediately when someone won
Key Takeaway
๐ฏ Key Insight: A tic-tac-toe state is valid only if it follows proper turn order AND the game stopped immediately when someone won. The moment a player gets three-in-a-row, no more moves can be made!
Time & Space Complexity
Time Complexity
O(1)
We check a fixed 3x3 board, so it's constant time despite nested loops
โ Linear Growth
Space Complexity
O(1)
Only using a few variables to count pieces and track winners
โ Linear Space
Constraints
- board.length == 3
- board[i].length == 3
- board[i][j] is either 'X', 'O', or ' '
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code