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 (
1or2) has a completed line onboard.
Step-by-step walkthrough
Map the 3x3 grid to flat array indices
We receive
board, a flat list of 9 integers where0means empty,1means Player X, and2means Player O. Each flat indexi(0 <= i <= 8) sits atrow = i // 3andcol = 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 | 8We must return
1if X owns three in a line,2if O owns three in a line, and0if 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.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 = 24cell reads). Instead of writing separateforloops 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_LINEStable makes every triplet easy to visually verify against the0..8grid 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 ]Avoid the two classic Tic-Tac-Toe bugs
Even on an 8-line loop, two subtle mistakes trip candidates up all the time:
- 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 | 0If 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`.- Never return
0inside the loop. One incomplete or mixed line only tells you that single line did not win. Only return0after all 8 triplets inWIN_LINEShave been checked and none succeeded.
- Three zeros are equal too! Suppose
Write `get_winner`
Unpack each triplet
(a, b, c), readowner = board[a], and returnowneras soon asowner != 0and bothboard[b]andboard[c]matchowner. If the loop finishes without returning, nobody owns a complete line, so return0.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 0Trace 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 0Complete 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_LINESis a fixed constant tuple table of 8 triplets, andget_winneruses only loop variables without allocating extra memory per call.
Edge cases
- Completely empty board (
[0] * 9): Every line starts withowner == 0, the loop finishes, andget_winnerreturns0. - Empty line appearing before a winning line: In
[0, 0, 0, 2, 2, 2, 1, 1, 0], row(0, 1, 2)is skipped byowner != 0so O's win on(3, 4, 5)is still detected. - Full board with no winner (draw): All 9 squares are
1or2, none of the 8 triplets has three identical marks, and the function returns0. - Full board won on the 9th move: Returns the winning player (
1or2), never0just 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: Checkingboard[a] == board[b] == board[c]alone treats(0, 0, 0)as a win for "player0" and exits on the first empty line. - Returning
0inside anelsebranch of theforloop: 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
rat3*r + c, columncat3*r + c, main diagonal4*k, and anti-diagonal2*k + 2. This uses the sameO(1)work and generalizes cleanly toN x N, though for3 x 3the explicitWIN_LINEStable 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 (
0or1) indicate whether a player occupies each square—and test(player_mask & line_mask) == line_maskagainst 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
Nrows (r * N + cfor0 <= c < N), each of theNcolumns (r * N + cfor0 <= r < N), the main diagonal (i * N + i), and the anti-diagonal (i * N + (N - 1 - i)), skipping any line whose leading square is0. That inspects2N + 2lines ofNsquares each, takingO(N^2)time (linear in theN^2grid cells) andO(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, andanti_diag = 0signed tallies incrementally on each placement, adding+1when X (1) claims(r, c)and-1when 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 allNsquares on that line belong to X (or O), so after placing at(r, c)you only inspectrows[r],cols[c], and—when(r, c)lies on a diagonal—diagandanti_diaginO(1)time andO(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 boardinO(N^2)time. To detect an early mathematical tie before every square is filled, a fast sufficient condition checks whether each of the2N + 2lines already contains both a1and a2(blocking both sides everywhere); on a3 x 3grid, 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 remaining0squares with alternating turns—checks every reachable finish in microseconds.
Follow-up questions
- How would you generalize this winner check to an arbitrary N-by-N grid?
- 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?
- How would you distinguish an unfinished game from a draw where neither player can win?
Similar questions
- LRU Cache With Value-Grouped Snapshots
- Nested 3x3 Ultimate Tic-Tac-Toe Engine
- Backend Architecture for a Multi-Agent Fintech Assistant
- Multi-Agent Corpus Research and Grounded Charting Platform
- Design a Cited Q&A Assistant over SEC Filings
- 2D Max Pooling with Source Coordinates