#794
Valid Tic-Tac-Toe State
MediumArrayMatrixHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
We can optimize the checking process by directly evaluating the winning conditions while counting 'X' and 'O'. This reduces the need for multiple passes over the board.
⚙️
Algorithm
3 steps- 1Step 1: Initialize counts for 'X' and 'O', and flags for winning conditions.
- 2Step 2: Iterate through the board to count 'X's and 'O's, and check winning conditions simultaneously.
- 3Step 3: Validate the counts and winning conditions to determine if the board state is valid.
solution.py23 lines
1def validTicTacToe(board):
2 x_count = o_count = 0
3 x_win = o_win = False
4 for i in range(3):
5 x_count += board[i].count('X')
6 o_count += board[i].count('O')
7 if board[i] == 'XXX' or board[0][i] == board[1][i] == board[2][i] == 'X':
8 x_win = True
9 if board[i] == 'OOO' or board[0][i] == board[1][i] == board[2][i] == 'O':
10 o_win = True
11 if board[0][0] == board[1][1] == board[2][2] == 'X' or board[0][2] == board[1][1] == board[2][0] == 'X':
12 x_win = True
13 if board[0][0] == board[1][1] == board[2][2] == 'O' or board[0][2] == board[1][1] == board[2][0] == 'O':
14 o_win = True
15 if o_count > x_count or x_count > o_count + 1:
16 return False
17 if x_win and o_win:
18 return False
19 if x_win and x_count != o_count + 1:
20 return False
21 if o_win and x_count != o_count:
22 return False
23 return Trueℹ
Complexity note: The time complexity is O(n) because we are making a single pass through the board to count and check wins, while the space complexity is O(1) as we are using a fixed amount of space.
- 1The count of 'X's must always be equal to or one more than the count of 'O's.
- 2A winning state for both players cannot occur simultaneously.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.