Design Tic-Tac-Toe - Problem

Design a Tic-Tac-Toe game that is played between two players on an n × n board. You may assume the following rules:

  • A move is guaranteed to be valid and is placed on an empty block.
  • Once a winning condition is reached, no more moves are allowed.
  • A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game.

Implement the TicTacToe class:

  • TicTacToe(int n) Initializes the object with the size of the board n.
  • int move(int row, int col, int player) Indicates that the player with id player plays at the cell (row, col) of the board. The move is guaranteed to be a valid move, and the two players alternate in making moves. Return 0 if there is no winner after the move, 1 if player 1 is the winner after the move, or 2 if player 2 is the winner after the move.

Input & Output

Example 1 — Player 1 Wins on 3x3 Board
$ Input: n = 3, moves: [[0,0,1], [0,2,2], [2,2,1], [1,1,2], [2,0,1], [1,0,2], [1,2,1]]
Output: [null,0,0,0,0,0,0,1]
💡 Note: Player 1 places marks at (0,0), (2,2), (2,0), (1,2). The last move (1,2) completes the anti-diagonal [0,0]→[1,1]→[2,2], so Player 1 wins.
Example 2 — Row Win on 2x2 Board
$ Input: n = 2, moves: [[0,0,1], [1,1,2], [0,1,1]]
Output: [null,0,0,1]
💡 Note: Player 1 fills the entire top row: (0,0) and (0,1). Two marks in a row on a 2x2 board means Player 1 wins.
Example 3 — Column Win
$ Input: n = 3, moves: [[0,0,1], [1,1,2], [1,0,1], [2,2,2], [2,0,1]]
Output: [null,0,0,0,0,1]
💡 Note: Player 1 places marks at (0,0), (1,0), (2,0) - filling the entire first column and winning.

Constraints

  • 2 ≤ n ≤ 100
  • player is 1 or 2
  • 0 ≤ row, col < n
  • (row, col) are unique for each different call to move
  • At most n2 calls will be made to move

Visualization

Tap to expand
Design Tic-Tac-Toe: Efficient Winner DetectionXOXXmove(0,0,1) → 0move(0,2,2) → 0move(1,1,1) → 0move(2,2,1) → 1Player 1 wins!Counter ArraysRows: [1, 1, 1]Cols: [1, 1, 1]Diag: 3 ✓Anti-diag: 1Sum = 3 = n!Instead of checking entire board, track sums: +1 for Player 1, -1 for Player 2O(1) time per move, O(n) space - much faster than O(n) checking!
Understanding the Visualization
1
Input
Board size n and sequence of player moves (row, col, player)
2
Process
Track sums for each row, column, and diagonal using counters
3
Output
Return winner (1 or 2) or 0 if game continues
Key Takeaway
🎯 Key Insight: Use mathematical sums instead of board scanning for instant winner detection
Asked in
Microsoft 45 Amazon 38 Google 32 Apple 28
125.0K Views
Medium Frequency
~25 min Avg. Time
2.2K 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