Detect Tic-Tac-Toe Termination on an n×n Grid
Arrays & HashingAuto-graded · 26 test casesLast 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:
- 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).
- 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:
0if the cell is unoccupied1if player 1 has marked it2if 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
ncells in that line contain the same non-zero value (1or2). A line filled entirely with0does not constitute a win. - The main diagonal consists of cells
(i, i)fori = 0, 1, ..., n-1. - The anti-diagonal consists of cells
(i, n-1-i)fori = 0, 1, ..., n-1. - Return
Trueif any line is complete, or if no cell remains empty. Otherwise returnFalse. - 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, wheren = len(board)and each row has exactlyncells- Each cell holds
0,1, or2 - 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The game terminates in exactly two scenarios:
- A player has won: Some line (row, column, or diagonal) contains
ncells all holding the same non-zero player mark. - The board is full: No empty cells remain, resulting in a stalemate.
For each potential winning line, examine the first cell. If it contains 0, that line cannot be a win, so skip it. Otherwise, verify that every remaining cell in the line matches the first cell. This approach avoids separately checking for player 1 and player 2, and automatically excludes lines filled entirely with zeros.
Systematically inspect all n rows, all n columns, the main diagonal, and the anti-diagonal. While scanning rows, track whether any 0 appears anywhere on the board. If no line produces a win, return whether the board was completely filled.
Correctness
- Line validation: A line wins if and only if all cells hold
1or all hold2. When the first cell is non-zero and all cells match it, the line must be uniform with a player mark. Conversely, if all cells are identical and non-zero, the first cell will be non-zero and match the rest. This test precisely captures the winning condition. - Complete coverage: The algorithm examines every row, every column, the cells at positions
(i, i), and the cells at positions(i, n-1-i). These represent all2n + 2possible winning lines, ensuring no victory goes undetected. - Early exit: If any line wins, the game is over regardless of remaining empty cells. Returning
Trueimmediately is safe. Thefullflag only determines the outcome when no line wins, and by that point all rows have been scanned, so it accurately reflects whether zeros exist. - Single cell case: When
n = 1, the lone cell forms every possible line. If non-zero, the row check succeeds. If zero, all line checks fail andfullremainsFalse. This matches the required behavior.
Complexity
Time: O(n²). Each line check takes O(n) time, and there are 2n + 2 lines to examine. For the maximum n = 1000, this involves roughly 2-4 million cell accesses, which executes quickly. This is also optimal: when the board has no winner and contains empty cells, every cell could influence the answer, requiring a full scan.
Space: O(1) auxiliary. Only a boolean flag and loop indices are maintained. No data structures proportional to n are allocated.
Solution
def is_game_over(board: list[list[int]]) -> bool:
n = len(board)
full = True
# Check rows (also track if any cell is empty)
for row in board:
if 0 in row:
full = False
f = row[0]
if f != 0 and row.count(f) == n:
return True
# Check columns
for c in range(n):
f = board[0][c]
if f != 0 and all(board[r][c] == f for r in range(n)):
return True
# Check main diagonal
f = board[0][0]
if f != 0 and all(board[i][i] == f for i in range(n)):
return True
# Check anti-diagonal
f = board[0][n - 1]
if f != 0 and all(board[i][n - 1 - i] == f for i in range(n)):
return True
# No winner found; game over only if board is full
return full