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
๐ŸŽฏ Referee's ScorecardPlayer A (X)Row 0: โšซ โšซ โšซ โ† WINNER!Row 1: โšซ โšช โšชRow 2: โšช โšช โšชCol 0: โšซ โšช โšชCol 1: โšซ โšช โšชCol 2: โšซ โšช โšชMain Diag: โšซ โšช โšชAnti Diag: โšซ โšช โšช๐Ÿ Game BoardXXXOO๐ŸŽŠ Result: Player A Wins!Instead of checking the entire board after each move,we track progress in each winning line. When any reaches 3, we have a winner!
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!
Asked in
Amazon 45 Microsoft 32 Google 28 Meta 22
52.2K Views
Medium Frequency
~15 min Avg. Time
1.8K 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