Report the Winner After Every Move on an n x n Tic-Tac-Toe Board
DatabricksSoftware Engineer · OnsiteLast updated
Process a sequence of alternating tic-tac-toe moves on an n x n board and report, after every move, whether player 1 or player 2 has just completed a full row, column, main diagonal or anti-diagonal. Tests efficient incremental win detection, diagonal indexing and correct handling of draws.
Two players play tic-tac-toe on an n × n board, a generalization of the classic 3 × 3 game. Player 1 makes the first move and the players then alternate; each move places the mover's mark on an empty cell. A player wins as soon as their marks fill an entire row, an entire column, the main diagonal or the anti-diagonal.
Given n and the moves in the order they are played, report the state of the game after every move.
Function Signature
def winner_after_each_move(n: int, moves: list[list[int]]) -> list[int]:
moves[i] = [row, col] is the cell, 0-indexed, taken by move i. Move i is made by player 1 when i is even and by player 2 when i is odd.
Rules
- The main diagonal is the cells
(i, i)and the anti-diagonal is the cells(i, n - 1 - i), for0 <= i < n. - The result after a move is the number of the player who has won (1 or 2), or 0 if nobody has won yet.
- The game stops at the first winning move: the input never contains a move after it, so only the last result can be nonzero.
- If the moves end without a winner (including a full board, which is a draw), every result is 0.
- When
n = 1, the first move fills a whole row, so player 1 wins immediately. - Return exactly one result per move, in move order.
Constraints
1 <= n <= 10001 <= len(moves) <= min(n * n, 100000)0 <= row, col < n, and no two moves use the same cell- No move follows a winning move
Examples
Example 1
Input: n = 3, moves = [[0, 0], [1, 1], [0, 1], [2, 2], [0, 2]]
Output: [0, 0, 0, 0, 1]
Player 1 takes (0, 0), (0, 1) and (0, 2) on moves 0, 2 and 4, completing the top row on the last move. Player 2's cells (1, 1) and (2, 2) lie on the main diagonal, but (0, 0) belongs to player 1.
Example 2
Input: n = 4, moves = [[0, 0], [0, 3], [1, 1], [1, 3], [2, 2], [2, 3], [3, 0], [3, 3]]
Output: [0, 0, 0, 0, 0, 0, 0, 2]
After move 4, player 1 holds three of the four main-diagonal cells, which is not a win on a 4 × 4 board. Player 2's last move completes column 3: (0, 3), (1, 3), (2, 3) and (3, 3).
Example 3
Input: n = 3, moves = [[0, 0], [1, 1], [0, 2], [0, 1], [2, 1], [1, 2], [1, 0], [2, 0], [2, 2]]
Output: [0, 0, 0, 0, 0, 0, 0, 0, 0]
The board fills up without a winner. The final position, by player number, is:
1 2 1
1 2 2
2 1 1
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.