KatInterview

Detect Tic-Tac-Toe Termination on an n×n Grid

Arrays & HashingAuto-graded · 26 test cases
MediumAuto-gradedArrays & Hashingarraysmatrixgame-simulation

Last updated

Tests scanning all rows, columns, and diagonals for a complete line of matching non-zero marks, and detecting a full board with no remaining moves.

You receive a snapshot of an n × n tic-tac-toe grid. Two players place marks on the grid, and the game ends under two conditions:

  1. Victory: One player claims an entire row, column, or diagonal (either the top-left to bottom-right diagonal or the top-right to bottom-left diagonal).
  2. Stalemate: Every cell on the grid is occupied, but neither player has won.

Determine whether the game has reached a terminal state (either a win or a stalemate).

Each cell contains:

  • 0 if the cell is unoccupied
  • 1 if player 1 has marked it
  • 2 if player 2 has marked it

Write a function that returns True if the game has ended, and False if play can continue.

Rules

  • A complete line (row, column, or diagonal) belongs to a player when all n cells in that line contain the same non-zero value (1 or 2). A line filled entirely with 0 does not constitute a win.
  • The main diagonal consists of cells (i, i) for i = 0, 1, ..., n-1.
  • The anti-diagonal consists of cells (i, n-1-i) for i = 0, 1, ..., n-1.
  • Return True if any line is complete, or if no cell remains empty. Otherwise return False.
  • You only need to detect termination. You do not need to identify the winner, and a completely filled grid that also contains a winning line is simply terminated.
  • Do not validate whether the grid could result from legal gameplay. Evaluate the grid state as provided, even if both players appear to have winning lines or the mark counts seem impossible.
  • When n = 1, the single cell forms a row, a column, and both diagonals simultaneously. The game terminates if and only if that cell is non-zero.

Constraints

  • 1 ≤ n ≤ 1000, where n = len(board) and each row has exactly n cells
  • Each cell holds 0, 1, or 2
  • The grid contains at most 1,000,000 cells total

Examples

Example 1

Input: is_game_over([[0, 0, 2], [1, 2, 1], [2, 1, 0]])

Output: True

Example 2

Input: is_game_over([[1, 2, 1], [1, 2, 2], [2, 1, 1]])

Output: True

Example 3

Input: is_game_over([[1, 2, 0], [0, 1, 0], [2, 0, 0]])

Output: False

Hints

Hint 1

Check each line by comparing all cells to the first cell in that line. If the first cell is zero, skip the line immediately.

Hint 2

Track whether you encounter any empty cell while scanning rows. If no line wins, the game terminates only when the board is completely full.

Hint 3

The anti-diagonal at row i is at column n-1-i, not n-i. Getting this indexing right matters for correctness.