Python coding

Tic-tac-toe referee in O(1) per move

Write a class TicTacToe(n) that referees a game of tic-tac-toe on an n × n board between players 1 and 2.

  • move(row, col, player) puts player's mark on the cell at row, col (0-indexed) and returns player if that gives them a whole row, a whole column or one of the board's two diagonals; otherwise it returns 0.

Every move is valid: it lands on an empty cell inside the board, and none comes after a win. Players don't have to alternate. move must take O(1) time, so rescanning the n cells of a line after each move is too slow.

The tests call the provided run_game(n, moves): it builds the referee, plays each [row, col, player] in order and returns the list of results.

Besides the tests, one large input (a 2,500 × 2,500 board, 10,000 moves) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • run_game(3, [[1,1,1],[0,0,2],[1,0,1],[2,2,2],[1,2,1]]) → [0,0,0,0,1]
  • run_game(3, [[0,0,1],[0,2,2],[1,0,1],[1,1,2],[2,2,1],[2,0,2]]) → [0,0,0,0,0,2]
  • run_game(1, [[0,0,2]]) → [2]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

A move can only complete its own row, its own column and the diagonals it sits on. You never need the board, only a summary of each line.

Hint 2

Keep one counter per row and per column, plus two for the diagonals. Player 1 adds 1 and player 2 subtracts 1, so a line totals n or -n only when one player owns all of it.

Hint 3

Cell (r, c) is on the main diagonal when r == c and on the other one when r + c == n - 1; the center of an odd board is on both.

Solution and why it works
pythonO(1) per move · O(n)
# --- your code ---
class TicTacToe:
    def __init__(self, n: int):
        self.n = n
        self.rows, self.cols = [0] * n, [0] * n     # player 1 adds 1 to a line, player 2 takes 1
        self.diag = self.anti = 0

    def move(self, row: int, col: int, player: int) -> int:
        step = 1 if player == 1 else -1
        self.rows[row] += step
        self.cols[col] += step
        if row == col:
            self.diag += step
        if row + col == self.n - 1:
            self.anti += step
        # a line reaches n * step only when all n of its cells are this player's
        lines = (self.rows[row], self.cols[col], self.diag, self.anti)
        return player if self.n * step in lines else 0


# --- provided: do not edit ---
def run_game(n: int, moves: list[list[int]]) -> list[int]:
    game = TicTacToe(n)
    return [game.move(row, col, player) for row, col, player in moves]

Store what the question needs, not the raw board: a move touches only its row, its column and at most two diagonals, so keep one total per line, +1 for player 1 and -1 for player 2. Each cell is marked once, so a line totals ±n exactly when one player holds all n cells: O(1) per move, O(n) memory instead of O(n²). The traps: counting marks without a sign (a full line of mixed marks is no win) and the anti-diagonal test, row + col == n - 1.