3x3 Tic-Tac-Toe Grid Winner Check

Hard · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Implement get_winner(board: List[int]) -> int to evaluate the outcome of a 3 x 3 Tic-Tac-Toe grid stored as a flat nine-integer list in row-major order, where flat index k (0 <= k < 9) maps to row k // 3 and column k % 3.

Each square uses an integer code: - 0 indicates an unmarked square. - 1 indicates a mark belonging to X. - 2 indicates a mark belonging to O.

A side wins whenever three of its marks occupy an entire horizontal row, vertical column, or three-cell diagonal. At most one side has achieved three in a line, although that side's final placement may simultaneously complete two intersecting lines.

Return: - 1 when X owns at least one complete three-cell line. - 2 when O owns at least one complete three-cell line. - 0 when neither side owns a complete line (covering both in-progress boards and nine-mark ties).

Examples

Example 1

Input: board = [1, 0, 2, 1, 2, 0, 2, 0, 1]
Output: 2

Laid out row by row as [1, 0, 2], [1, 2, 0], and [2, 0, 1], O (2) holds positions 2, 4, and 6 along the top-right-to-bottom-left diagonal, so get_winner returns 2.

Example 2

Input: board = [0, 1, 2, 2, 1, 1, 1, 2, 0]
Output: 0

Across rows [0, 1, 2], [2, 1, 1], and [1, 2, 0], every row, column, and diagonal is either partially unmarked or split between 1 and 2, so neither side has won and the function returns 0.

Constraints

  • len(board) == 9
  • Every entry board[k] belongs to {0, 1, 2}.
  • At most one player (1 or 2) has a completed line on board.

Step-by-step walkthrough

  1. Map the 3x3 grid to flat array indices

    We receive board, a flat list of 9 integers where 0 means empty, 1 means Player X, and 2 means Player O. Each flat index i (0 <= i <= 8) sits at row = i // 3 and col = i % 3—equivalently, index = 3 * row + col:

    (row, col) coordinates        Flat array indices
    ----------------------        ------------------
    (0,0) | (0,1) | (0,2)            0  |  1  |  2
    ------+-------+------         ------+-----+------
    (1,0) | (1,1) | (1,2)            3  |  4  |  5
    ------+-------+------         ------+-----+------
    (2,0) | (2,1) | (2,2)            6  |  7  |  8
    

    We must return 1 if X owns three in a line, 2 if O owns three in a line, and 0 if nobody has won yet (whether the board is partially empty or a full-board draw). Note that in a legal Tic-Tac-Toe game play stops immediately when a line is completed, so both players cannot simultaneously win; if one player completes two crossing lines on their winning move, both lines belong to that same player.

  2. List all 8 winning lines as index triplets

    On a fixed 3x3 board there are only 8 possible winning lines: 3 rows, 3 columns, and 2 diagonals (at most 8 * 3 = 24 cell reads). Instead of writing separate for loops and index formulas for rows, columns, and diagonals, we can list the 8 index triplets once as data and inspect them with a single clean loop:

    Rows (step +1 across):    (0, 1, 2),  (3, 4, 5),  (6, 7, 8)
    Columns (step +3 down):   (0, 3, 6),  (1, 4, 7),  (2, 5, 8)
    Main diagonal (step +4):  (0, 4, 8)
    Anti-diagonal (step +2):  (2, 4, 6)
    

    Putting the rules into a constant WIN_LINES table makes every triplet easy to visually verify against the 0..8 grid diagram above.

    # WIN_LINES: all 8 index triplets into `board` (flat index = 3 * row + col):
    #   0 | 1 | 2
    #   3 | 4 | 5
    #   6 | 7 | 8
    WIN_LINES = [
        (0, 1, 2), (3, 4, 5), (6, 7, 8),  # 3 horizontal rows
        (0, 3, 6), (1, 4, 7), (2, 5, 8),  # 3 vertical columns
        (0, 4, 8), (2, 4, 6),             # main diagonal and anti-diagonal
    ]
    
  3. Avoid the two classic Tic-Tac-Toe bugs

    Even on an 8-line loop, two subtle mistakes trip candidates up all the time:

    1. Three zeros are equal too! Suppose board = [0, 0, 0, 1, 1, 1, 2, 2, 0]:

    text 0 | 0 | 0 <- top row (0, 1, 2) has three matching 0s! 1 | 1 | 1 <- Player X (1) actually won on the middle row (3, 4, 5) 2 | 2 | 0

    If you write `if board[a] == board[b] == board[c]: return board[a]` without checking `board[a] != 0`, the top row matches `0 == 0 == 0` and immediately returns `0`, missing X's real win on row 1! Always require `owner != 0`.
    
    1. Never return 0 inside the loop. One incomplete or mixed line only tells you that single line did not win. Only return 0 after all 8 triplets in WIN_LINES have been checked and none succeeded.
  4. Write `get_winner`

    Unpack each triplet (a, b, c), read owner = board[a], and return owner as soon as owner != 0 and both board[b] and board[c] match owner. If the loop finishes without returning, nobody owns a complete line, so return 0.

    def get_winner(board: List[int]) -> int:
        for a, b, c in WIN_LINES:
            owner = board[a]
            # Skip empty starting squares (0) so three empty cells (0, 0, 0) never count as a win.
            if owner != 0 and board[b] == owner and board[c] == owner:
                return owner
    
        # Return 0 only after all 8 lines fail (covers both unfinished games and full-board draws).
        return 0
    
  5. Trace Example 1 and Example 2

    Example 1: board = [1, 0, 2, 1, 2, 0, 2, 0, 1]

    Board:          Line check trace:
    1 | 0 | 2       (0, 1, 2) -> (1, 0, 2)  mixed
    1 | 2 | 0       (3, 4, 5) -> (1, 2, 0)  mixed
    2 | 0 | 1       (6, 7, 8) -> (2, 0, 1)  mixed
                    (0, 3, 6) -> (1, 1, 2)  mixed
                    (1, 4, 7) -> (0, 2, 0)  owner == 0 -> skipped!
                    (2, 5, 8) -> (2, 0, 1)  mixed
                    (0, 4, 8) -> (1, 2, 1)  mixed
                    (2, 4, 6) -> (2, 2, 2)  owner = 2 != 0, all match -> return 2!
    

    Example 2: board = [0, 1, 2, 2, 1, 1, 1, 2, 0]

    Board:          Line check trace:
    0 | 1 | 2       (0, 1, 2) -> (0, 1, 2)  owner == 0 -> skipped!
    2 | 1 | 1       (3, 4, 5) -> (2, 1, 1)  mixed
    1 | 2 | 0       (6, 7, 8) -> (1, 2, 0)  mixed
                    (0, 3, 6) -> (0, 2, 1)  owner == 0 -> skipped!
                    (1, 4, 7) -> (1, 1, 2)  mixed
                    (2, 5, 8) -> (2, 1, 0)  mixed
                    (0, 4, 8) -> (0, 1, 0)  owner == 0 -> skipped!
                    (2, 4, 6) -> (2, 1, 1)  mixed
                    All 8 lines checked -> return 0
    
  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    # WIN_LINES: all 8 index triplets into `board` (flat index = 3 * row + col):
    #   0 | 1 | 2
    #   3 | 4 | 5
    #   6 | 7 | 8
    WIN_LINES = [
        (0, 1, 2), (3, 4, 5), (6, 7, 8),  # 3 horizontal rows
        (0, 3, 6), (1, 4, 7), (2, 5, 8),  # 3 vertical columns
        (0, 4, 8), (2, 4, 6),             # main diagonal and anti-diagonal
    ]
    
    
    def get_winner(board: List[int]) -> int:
        for a, b, c in WIN_LINES:
            owner = board[a]
            # Skip empty starting squares (0) so three empty cells (0, 0, 0) never count as a win.
            if owner != 0 and board[b] == owner and board[c] == owner:
                return owner
    
        # Return 0 only after all 8 lines fail (covers both unfinished games and full-board draws).
        return 0
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine holding 8 cardboard stencils over a 3x3 Tic-Tac-Toe grid—3 horizontal strips, 3 vertical strips, and 2 diagonal strips. Each stencil exposes 3 squares in the flat array (stored in row-major order, meaning the 2D grid is laid out row by row so (row, col) sits at index 3 * row + col). If any stencil reveals three matching non-empty marks (1, 1, 1 or 2, 2, 2), that player has won; if none of the 8 stencils matches, the result is 0.

Writing separate nested if/else blocks or index loops for rows, columns, and diagonals repeats the same check in several places and invites index typos—especially on the anti-diagonal (2, 4, 6). Worse, checking board[a] == board[b] == board[c] without requiring board[a] != 0 mistakes an empty line (0, 0, 0) for a winner of 0 and returns early before discovering a real win further down the board. Storing the 8 triplets in a data-driven table—plain data processed by one uniform loop—eliminates duplicated logic completely.

Walk through board = [0, 0, 0, 1, 1, 1, 2, 2, 0]: - Check (0, 1, 2): values are (0, 0, 0). Because owner == 0, we skip this empty line instead of returning 0. - Check (3, 4, 5): values are (1, 1, 1). Here owner == 1 != 0 and both board[4] and board[5] equal 1, so we immediately return 1 (Player X).

Complexity

  • Time: O(1). On a fixed 3x3 board, the loop inspects at most 8 index triplets of 3 squares each (at most 24 list lookups), which is bounded by a small constant independent of any input values.
  • Space: O(1). WIN_LINES is a fixed constant tuple table of 8 triplets, and get_winner uses only loop variables without allocating extra memory per call.

Edge cases

  • Completely empty board ([0] * 9): Every line starts with owner == 0, the loop finishes, and get_winner returns 0.
  • Empty line appearing before a winning line: In [0, 0, 0, 2, 2, 2, 1, 1, 0], row (0, 1, 2) is skipped by owner != 0 so O's win on (3, 4, 5) is still detected.
  • Full board with no winner (draw): All 9 squares are 1 or 2, none of the 8 triplets has three identical marks, and the function returns 0.
  • Full board won on the 9th move: Returns the winning player (1 or 2), never 0 just because no empty cells remain.
  • Crossing winning lines (e.g., X completes both a row and a column on one move): Both lines belong to the same player, so returning on the first matching triplet gives the exact right winner.

Common mistakes

  • Omitting owner != 0: Checking board[a] == board[b] == board[c] alone treats (0, 0, 0) as a win for "player 0" and exits on the first empty line.
  • Returning 0 inside an else branch of the for loop: Exits after testing only (0, 1, 2) and misses wins on the other 7 lines.
  • Anti-diagonal index typos: Writing (2, 4, 8) or (3, 4, 5) instead of (2, 4, 6) for top-right (0, 2) -> center (1, 1) -> bottom-left (2, 0).
  • Forgetting diagonals altogether: Checking only the 3 rows and 3 columns misses 2 of the 8 ways to win.

Alternative approaches

  • Computed row/column/diagonal loops: Check row r at 3*r + c, column c at 3*r + c, main diagonal 4*k, and anti-diagonal 2*k + 2. This uses the same O(1) work and generalizes cleanly to N x N, though for 3 x 3 the explicit WIN_LINES table is shorter and easier to eyeball.
  • Bitmasks: Represent X's squares and O's squares as two 9-bit bitmasks—integers whose individual binary bits (0 or 1) indicate whether a player occupies each square—and test (player_mask & line_mask) == line_mask against 8 precomputed integer masks (0b000000111, etc.). Very fast in game engines, though less readable in a standard coding interview.

Follow-up questions

  • How would you generalize this winner check to an arbitrary N-by-N grid? Instead of hard-coding 8 triplets, scan each of the N rows (r * N + c for 0 <= c < N), each of the N columns (r * N + c for 0 <= r < N), the main diagonal (i * N + i), and the anti-diagonal (i * N + (N - 1 - i)), skipping any line whose leading square is 0. That inspects 2N + 2 lines of N squares each, taking O(N^2) time (linear in the N^2 grid cells) and O(1) auxiliary space when checked directly in place.
  • Suppose moves arrive one by one in a live match—how can you determine after each move whether someone just won in O(1) time? Maintain rows = [0] * N, cols = [0] * N, diag = 0, and anti_diag = 0 signed tallies incrementally on each placement, adding +1 when X (1) claims (r, c) and -1 when O (2) claims (r, c). Because each cell is marked once at most, a line's tally reaches +N (or -N) if and only if all N squares on that line belong to X (or O), so after placing at (r, c) you only inspect rows[r], cols[c], and—when (r, c) lies on a diagonal—diag and anti_diag in O(1) time and O(N) total space.
  • How would you distinguish an unfinished game from a draw where neither player can win? For a completed nine-move tie where zero legal placements remain, test get_winner(board) == 0 and 0 not in board in O(N^2) time. To detect an early mathematical tie before every square is filled, a fast sufficient condition checks whether each of the 2N + 2 lines already contains both a 1 and a 2 (blocking both sides everywhere); on a 3 x 3 grid, if you also want to catch positions where one unblocked line remains yet its owner lacks enough remaining turns to fill it, a tiny depth-first game tree search—recursively exploring remaining 0 squares with alternating turns—checks every reachable finish in microseconds.

Follow-up questions

Similar questions

More Hebbia interview questions

All 6 Hebbia questions →