Design Tic-Tac-Toe - Problem
You're building an intelligent Tic-Tac-Toe game that can handle boards of any size! ๐ฏ
Your task is to design a TicTacToe class that can efficiently determine winners on an n ร n board. The game follows these rules:
- ๐ Players alternate turns placing their marks (Player 1 and Player 2)
- ๐ฏ A player wins by getting n marks in a row - horizontally, vertically, or diagonally
- โ All moves are guaranteed to be valid (no need to check bounds or occupied cells)
- ๐ Once someone wins, no more moves are allowed
Your Challenge: Implement the class efficiently! The naive approach of checking the entire board after each move would be O(nยฒ) - but can you do better? ๐
Class Interface:
TicTacToe(int n) // Initialize nรn board
int move(row, col, player) // Make move, return winner (0=none, 1=player1, 2=player2) Input & Output
example_1.py โ Basic 3ร3 Game
$
Input:
TicTacToe(3)
move(0, 0, 1) โ 0
move(0, 2, 2) โ 0
move(2, 2, 1) โ 0
move(1, 1, 2) โ 0
move(2, 0, 1) โ 0
move(1, 0, 2) โ 2
โบ
Output:
Player 2 wins on the last move
๐ก Note:
Player 2 gets three in the first column: (0,2)โX, (1,0)โX, (1,1)โX, forming a winning line vertically in column 0.
example_2.py โ Diagonal Win
$
Input:
TicTacToe(3)
move(0, 0, 1) โ 0
move(0, 1, 2) โ 0
move(1, 1, 1) โ 0
move(0, 2, 2) โ 0
move(2, 2, 1) โ 1
โบ
Output:
Player 1 wins with main diagonal
๐ก Note:
Player 1 achieves victory by occupying the main diagonal: positions (0,0), (1,1), and (2,2).
example_3.py โ Larger Board
$
Input:
TicTacToe(4)
move(0, 0, 1) โ 0
move(1, 1, 2) โ 0
move(0, 1, 1) โ 0
move(1, 2, 2) โ 0
move(0, 2, 1) โ 0
move(1, 3, 2) โ 0
move(0, 3, 1) โ 1
โบ
Output:
Player 1 wins entire top row
๐ก Note:
On a 4ร4 board, Player 1 fills the entire first row with 4 consecutive marks to win.
Visualization
Tap to expand
Understanding the Visualization
1
Traditional Approach
After each move, scan entire board checking every possible winning line
2
Smart Realization
We only need to track progress toward victory, not the full board state
3
Counter Magic
Each counter represents progress: +1 for Player 1, -1 for Player 2
4
Instant Victory
When any counter hits ยฑn, we have an immediate winner!
Key Takeaway
๐ฏ Key Insight: Instead of asking 'What's on the board?', ask 'How close is each player to winning?' - this transforms an O(n) problem into O(1) magic!
Time & Space Complexity
Time Complexity
O(1)
Each move only updates constant number of counters and checks for winners instantly
โ Linear Growth
Space Complexity
O(n)
We store 2n+2 counters (n rows + n columns + 2 diagonals)
โก Linearithmic Space
Constraints
- 2 โค n โค 100
- player is either 1 or 2
- 0 โค row, col < n
- (row, col) are valid coordinates of an empty cell
- At most n2 calls will be made to move
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code