Find Winner on a Tic Tac Toe Game - Problem
You're given the sequence of moves in a classic Tic-Tac-Toe game and need to determine the current game state!
In this 3ร3 grid game:
- Player A always goes first and places '
X' marks - Player B goes second and places '
O' marks - Players alternate turns placing their marks in empty squares
- The game ends when someone gets three in a row (horizontally, vertically, or diagonally)
- If all 9 squares are filled without a winner, it's a draw
Your task: Given an array moves where moves[i] = [row, col] represents the i-th move, return:
"A"if player A wins"B"if player B wins"Draw"if the game ended in a tie"Pending"if the game is still ongoing
Example: moves = [[0,0],[2,0],[1,1],[1,0],[2,2]] results in A winning with a diagonal!
Input & Output
example_1.py โ A Wins Diagonally
$
Input:
moves = [[0,0],[2,0],[1,1],[1,0],[2,2]]
โบ
Output:
"A"
๐ก Note:
A places X at (0,0), (1,1), and (2,2) forming a diagonal. The game ends after A's third move with A as the winner.
example_2.py โ Draw Game
$
Input:
moves = [[0,0],[1,1],[0,1],[0,2],[1,0],[2,0],[1,2],[2,1],[2,2]]
โบ
Output:
"Draw"
๐ก Note:
All 9 squares are filled but neither player achieved three in a row. The game ends in a draw.
example_3.py โ Pending Game
$
Input:
moves = [[0,0],[1,1],[2,0],[1,0],[1,2],[2,2]]
โบ
Output:
"Pending"
๐ก Note:
After 6 moves, no player has three in a row and there are still empty squares. The game is still ongoing.
Constraints
- 1 โค moves.length โค 9
- moves[i].length == 2
- 0 โค moves[i][j] โค 2
- There are no repeated moves
- All moves are valid according to tic-tac-toe rules
Visualization
Tap to expand
Understanding the Visualization
1
Set Up Scorecard
Create progress counters for both players across all 8 winning lines
2
Process Each Move
For each move, increment the current player's counters for affected lines
3
Check for Victory
If any counter reaches 3, declare that player the winner immediately
4
Determine Final State
If no winner after all moves, check if it's a draw or still pending
Key Takeaway
๐ฏ Key Insight: Track winning progress, not board state - it's faster and more elegant!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code