Design Tic-Tac-Toe
❌ What is Tic-Tac-Toe? Two players take turns writing their mark (X or O) into an empty cell of a square grid. The first player to fill a whole row, a whole column or a diagonal with their own mark wins. If the grid fills up first, the game is a draw.
Tic-tac-toe is the smallest game interviewers ask for, which is exactly why it is useful. There is no room to hide behind a big class diagram, so the interviewer watches how you turn "two players and a grid" into clear rules, how you reject bad moves, and whether you notice that checking for a winner after every move can be made almost free. The board is N by N, so the classic 3 by 3 game is just one setting, and the interesting part is a win check that does not slow down as N grows.
Requirements
"Design a tic-tac-toe game for two players on an N by N board."
That one line hides most of the rules. Ask before you draw a single class.
Clarifying Questions
You: How big is the board, and what counts as a win?
Interviewer: The board is N by N, with N given when the game starts. A player wins by owning all N cells of a row, a column, or one of the two main diagonals.
You: Who moves first, and do we enforce turns?
Interviewer: Player 1 always starts, then they alternate. If the wrong player tries to move, reject it.
You: What should happen on an illegal move, like a taken cell or a cell outside the board?
Interviewer: Reject it and change nothing. The same player is still on turn. Don't throw; return an error value the caller can check.
You: How does the game end, and what happens after that?
Interviewer: It ends when someone wins or when the board is full. After that, every move is rejected.
You: Is there a user interface or a computer opponent?
Interviewer: No UI. The game is a class that another layer calls with a row, a column and a player. A computer player might come up later.
You: One game at a time, or many?
Interviewer: One game per object. Don't worry about threads.
The third answer settles an important design choice: a rejected move is a normal outcome, not a crash. Players click the wrong cell all the time, so move returns a result code instead of raising an exception. Ask this early, because it decides the signature of the main method.
💡 Interview tip: Ask what the move method should return. "The result of the move" (keep going, win, draw, rejected) is a much better contract than "nothing, and you call
get_winner()afterwards", because the caller learns everything from one call and cannot forget to check.
Final Requirements
- The board is N by N, with N chosen when the game is created. Rows and columns are numbered from 0.
- Player 1 moves first, then players alternate.
- A move names a row, a column and a player. It is rejected, with no change at all, if the game is over, it is not that player's turn, the cell is off the board, or the cell is taken.
- After each move, if the player owns the whole row, column or diagonal through that cell, they win.
- If a move fills the last empty cell without winning, the game is a draw.
- Each move returns its result: game continues, player 1 wins, player 2 wins, draw, or rejected.
- Anyone can ask whose turn it is (or learn that the game is over).
Out of scope
- A user interface, input parsing and printing the board.
- Computer opponents (we come back to this in Extensibility).
- Undo, saving a game, and many games at once (also in Extensibility).
- Timers and networked play.
Entities and Relationships
Underline the nouns in the requirements: game, board, cell, player, move, row, column, diagonal, result. Keep the ones that hold state or enforce a rule.
- TicTacToe: the game and the entry point. It knows whose turn it is and whether the game is over, and it is the only class the caller talks to.
- Board: the grid of cells. It answers "is this cell on the board?" and "is it empty?", records marks, and knows when it is full.
- WinTracker: the part that decides whether the latest move completed a line. It is its own entity because it is the one piece with a clever idea in it, and it deserves to be tested on its own.
- Status: an enum for the state of the game: in progress, player 1 won, player 2 won, draw.
Several nouns sound like classes but are not worth one:
- Player is just the number 1 or 2. A player has no behavior in this problem; the game only needs to know whose turn it is. When a computer player shows up, a
Playerclass earns its place, and not before. - Cell is an integer in the grid: 0 for empty, 1 or 2 for a mark. A
Cellobject per square would hold one number and nothing else. - Move is the three arguments of
move. We do not store moves yet. If we add undo or replays, a smallMoverecord appears then. - Row, column and diagonal are indexes, not objects.
Who owns whom:
| Owner | Owns | How many |
|---|---|---|
| TicTacToe | Board | exactly one |
| TicTacToe | WinTracker | exactly one |
| TicTacToe | Status | one current value |
| Board | cells | N × N integers |
Class Design
We go top down, from the class the caller uses. The orchestrator should read like the rules: check the move, place it, ask whether it won, update the turn. Grid details and line counting belong to the classes below it.
TicTacToe
The orchestrator. It enforces turns and the end of the game, and it turns every move into a result code.
class TicTacToe:
board: Board # requirement 1
wins: WinTracker # requirement 4
turn: int # 1 or 2, requirement 2
status: Status # requirements 5 and 6
def __init__(self, n: int): ...
def move(self, row: int, col: int, player: int) -> int: ... # 0, 1, 2, 3 or -1
def current_player(self) -> int: ... # 1, 2, or 0 when over
turn and status are two separate fields on purpose. turn says who moves next while the game is running; status says whether it is still running. Folding them into one value ("turn 0 means over") saves a field but makes every check harder to read.
Board
The grid and nothing else. It knows the geometry of the board, not the rules of the game.
class Board:
n: int
cells: List[List[int]] # 0 empty, 1 or 2 a mark
filled: int # how many cells hold a mark
def in_bounds(self, row: int, col: int) -> bool: ...
def is_empty(self, row: int, col: int) -> bool: ...
def place(self, row: int, col: int, player: int) -> None: ...
def is_full(self) -> bool: ...
filled is a counter so that is_full (requirement 5) is one comparison instead of a scan of N² cells. place does not check anything: the game has already validated the move, and keeping the board "dumb" means the rules live in one place.
WinTracker
The class that answers requirement 4. It keeps one running number per line, which is the idea we build up to in the Implementation section.
class WinTracker:
n: int
rows: List[int] # one sum per row
cols: List[int] # one sum per column
diagonal: int # cells where row == col
anti_diagonal: int # cells where row + col == n - 1
def record(self, row: int, col: int, player: int) -> bool: ... # True if the move won
It never looks at the grid. It only needs to hear about each move once, which is why the game calls record right after place.
Status
class Status(Enum):
IN_PROGRESS = 0
PLAYER_1_WINS = 1
PLAYER_2_WINS = 2
DRAW = 3
The values match the codes move returns, so returning the result is just self.status.value. A rejected move is not a status of the game (the game did not change), so it is a separate constant, INVALID = -1.
Implementation
There is really one method to write, move. We write its happy path first, then spend most of our time on the part that makes this problem interesting: deciding whether the move won.
Making a move
def move(self, row: int, col: int, player: int) -> int:
if self.status != Status.IN_PROGRESS or player != self.turn:
return INVALID # game over, or not your turn (req. 2, 3)
if not self.board.in_bounds(row, col) or not self.board.is_empty(row, col):
return INVALID # off the board, or taken (req. 3)
self.board.place(row, col, player)
if self.wins.record(row, col, player): # requirement 4
self.status = Status.PLAYER_1_WINS if player == 1 else Status.PLAYER_2_WINS
elif self.board.is_full(): # requirement 5
self.status = Status.DRAW
else:
self.turn = 3 - self.turn # 1 -> 2, 2 -> 1
return self.status.value
Three details are worth saying out loud:
- All checks come before any change. A rejected move returns before
place, so it cannot leave half a move behind. This is what "reject it and change nothing" means in code. - The bounds check comes before the emptiness check.
is_empty(5, 5)on a 3 by 3 board would index outside the grid. Theorstops at the first failing check, so the order matters. - Win is checked before draw. A move can fill the last cell and complete a line at the same time. That is a win, and checking
is_fullfirst would wrongly call it a draw.
current_player is one line:
def current_player(self) -> int:
return self.turn if self.status == Status.IN_PROGRESS else 0
Checking for a winner
After each move we need to know whether the player now owns a whole line. There are three ways to answer, and they differ only in how much of the board they look at.
Bad Solution: scan the whole board
Approach
After every move, check every row, every column and both diagonals for a line of one player.
def has_winner(cells: List[List[int]], n: int) -> int:
lines = [[cells[r][c] for c in range(n)] for r in range(n)] # rows
lines += [[cells[r][c] for r in range(n)] for c in range(n)] # columns
lines.append([cells[i][i] for i in range(n)])
lines.append([cells[i][n - 1 - i] for i in range(n)])
for line in lines:
if line[0] != 0 and all(x == line[0] for x in line):
return line[0]
return 0
Challenges
It is correct and easy to explain, so it is a fine first draft on a 3 by 3 board. But every move reads every cell: O(N²) work per move. On a 100 by 100 board that is about 10,000 reads for each of up to 10,000 moves. It also ignores something we know for free: only the player who just moved can have just won, and only along lines that pass through the cell they just took.
Good Solution: check only the lines through the last move
Approach
A new win must include the new mark. So look only at the move's row, its column, and the diagonals it lies on.
def wins_after(cells: List[List[int]], n: int, row: int, col: int, player: int) -> bool:
if all(cells[row][c] == player for c in range(n)):
return True
if all(cells[r][col] == player for r in range(n)):
return True
if row == col and all(cells[i][i] == player for i in range(n)):
return True
return row + col == n - 1 and all(cells[i][n - 1 - i] == player for i in range(n))
Challenges
Now each move reads at most 4N cells: O(N) instead of O(N²). This is what most candidates write, and it is a good answer. The catch is that we still re-read cells we have already seen many times. A row with N - 1 of our marks gets read again in full on every move in that row. Your interviewer will often ask, "can you make the win check constant time?"
Great Solution: running counters per line
Approach
Keep one number per line and update it as moves happen. Each time player 1 marks a cell, add 1 to that cell's row, its column, and its diagonals. Each time player 2 marks a cell, subtract 1. A line belongs entirely to player 1 when its sum reaches N, and entirely to player 2 when it reaches -N.
def record(self, row: int, col: int, player: int) -> bool:
delta = 1 if player == 1 else -1
self.rows[row] += delta
self.cols[col] += delta
if row == col:
self.diagonal += delta
if row + col == self.n - 1:
self.anti_diagonal += delta
target = delta * self.n
return (self.rows[row] == target or self.cols[col] == target
or (row == col and self.diagonal == target)
or (row + col == self.n - 1 and self.anti_diagonal == target))
Challenges
Why does a sum of N prove that one player owns the whole line? A line has N cells, and each contributes +1, -1 or 0 (empty). The only way to add up to N is for every cell to be +1. So a sum of N means "all N cells are player 1's", and a mixed line can never reach N or -N. That one sentence is what the interviewer wants to hear.
Each move is now a handful of additions and comparisons: O(1) time, with O(N) extra memory for the counters (2N + 2 numbers). The trade-off is that the trick depends on the rule "a win is a full line". If the rules change to "K in a row on a bigger board" (Gomoku), the sums no longer tell us anything, and we go back to the Good solution's idea of looking around the last move. We cover that in Extensibility.
Two smaller choices are worth defending:
- Why +1 and -1 instead of two sets of counters? Two sets (one per player) also work and are a bit easier to read. The signed version halves the memory and matches the "a line is won when it is all one sign" picture. Either is a good answer; pick one and say why.
- Why check the diagonals only when the cell is on them? If the move is off the diagonal, the diagonal sum did not change, so it cannot have just reached N. The condition keeps the meaning clear: we only report lines that this move touched.
⚠️ Common mistake: Updating the diagonal counter for every move, or forgetting that the center cell of an odd board lies on both diagonals. Use two independent
ifstatements, notif/elif, so the center updates both.
Edge cases
Walk through these before you say you are done. Each one is a line that already exists in move or record:
- Wrong player: player 2 tries to start, or someone moves twice. Rejected by
player != self.turn, and the turn does not change. - Taken cell or off the board: rejected before any state changes. The bounds check runs first, so no index error.
- Move after the game ended: the
statuscheck comes first, so even a valid-looking cell is rejected. - Win on the last cell:
recordruns beforeis_full, so the result is a win, not a draw. - N = 1: the first move fills a row, a column and both diagonals at once. Player 1 wins immediately, and the code needs no special case.
- A player number other than 1 or 2: it can never equal
self.turn, so it is rejected.recordnever sees it, which matters because it treats "not 1" as player 2.
Verification
Let's trace a 3 by 3 game, the same sequence as the first practice test. The counters are shown only where they change.
| # | Call | What happens | Returns |
|---|---|---|---|
| 1 | move(0, 0, 1) |
Player 1 takes a corner. rows[0] = 1, cols[0] = 1, diagonal = 1. Turn passes to 2 | 0 |
| 2 | move(0, 0, 2) |
Cell taken: rejected, still player 2's turn | -1 |
| 3 | move(1, 1, 1) |
Not player 1's turn: rejected | -1 |
| 4 | move(1, 1, 2) |
Center: rows[1] = -1, cols[1] = -1, diagonal = 0, anti_diagonal = -1 | 0 |
| 5 | current_player() |
Game in progress, turn is 1 | 1 |
| 6 | move(0, 1, 1) |
rows[0] = 2, cols[1] = 0 | 0 |
| 7 | move(2, 2, 2) |
rows[2] = -1, cols[2] = -1, diagonal = -1 | 0 |
| 8 | move(0, 2, 1) |
rows[0] = 3 = N: player 1 owns the top row | 1 |
| 9 | move(1, 0, 2) |
Game is over: rejected | -1 |
| 10 | current_player() |
Status is PLAYER_1_WINS | 0 |
Step 4 shows the counters doing their job: the diagonal had player 1's corner (+1) and now player 2's center (-1), so it sums to 0, which correctly says "nobody can win this line any more by sum alone". Step 8 is the whole point of the design: we learned about the win from one comparison, without reading a single cell of the grid.
Complete Code
Here is the full design in each language, the same code the practice tests run against.
from enum import Enum
from typing import List
INVALID = -1 # returned by move() when the move is rejected
class Status(Enum):
IN_PROGRESS = 0
PLAYER_1_WINS = 1
PLAYER_2_WINS = 2
DRAW = 3
class Board:
"""The grid. 0 is an empty cell, 1 and 2 are the players' marks."""
def __init__(self, n: int):
self.n = n
self.cells: List[List[int]] = [[0] * n for _ in range(n)]
self.filled = 0
def in_bounds(self, row: int, col: int) -> bool:
return 0 <= row < self.n and 0 <= col < self.n
def is_empty(self, row: int, col: int) -> bool:
return self.cells[row][col] == 0
def place(self, row: int, col: int, player: int) -> None:
self.cells[row][col] = player
self.filled += 1
def is_full(self) -> bool:
return self.filled == self.n * self.n
class WinTracker:
"""A running sum per line: +1 for each mark of player 1, -1 for player 2.
A line belongs to one player exactly when its sum is n or -n."""
def __init__(self, n: int):
self.n = n
self.rows = [0] * n
self.cols = [0] * n
self.diagonal = 0 # cells where row == col
self.anti_diagonal = 0 # cells where row + col == n - 1
def record(self, row: int, col: int, player: int) -> bool:
"""Adds a mark and returns True if it completes a line."""
delta = 1 if player == 1 else -1
self.rows[row] += delta
self.cols[col] += delta
if row == col:
self.diagonal += delta
if row + col == self.n - 1:
self.anti_diagonal += delta
target = delta * self.n
return (self.rows[row] == target or self.cols[col] == target
or (row == col and self.diagonal == target)
or (row + col == self.n - 1 and self.anti_diagonal == target))
class TicTacToe:
def __init__(self, n: int):
self.board = Board(n)
self.wins = WinTracker(n)
self.turn = 1 # player 1 always starts
self.status = Status.IN_PROGRESS
def move(self, row: int, col: int, player: int) -> int:
if self.status != Status.IN_PROGRESS or player != self.turn:
return INVALID # the game is over, or it is not this player's turn
if not self.board.in_bounds(row, col) or not self.board.is_empty(row, col):
return INVALID # off the board, or the cell is taken
self.board.place(row, col, player)
if self.wins.record(row, col, player):
self.status = Status.PLAYER_1_WINS if player == 1 else Status.PLAYER_2_WINS
elif self.board.is_full():
self.status = Status.DRAW
else:
self.turn = 3 - self.turn # 1 -> 2, 2 -> 1
return self.status.value
def current_player(self) -> int:
return self.turn if self.status == Status.IN_PROGRESS else 0
Try it yourself: the Practice button above runs your code against the same interface.
Extensibility
Once move works, interviewers use the remaining time to change a rule and watch where the change lands. A good answer names the class that absorbs it and says which classes stay untouched.
1) How would you support "K in a row" on a bigger board?
Gomoku-style rules say you win with K marks in a row (say 5) on a board much larger than K (say 15 by 15). The running sums break here: a row of 15 can hold five of your marks in a row and still have a mixed sum. Instead we go back to the idea from the Good solution, looking only around the last move, but we count outward in each direction until the line breaks.
DIRECTIONS = [(0, 1), (1, 0), (1, 1), (1, -1)] # row, column, two diagonals
def connects(cells: List[List[int]], row: int, col: int, k: int) -> bool:
n, player = len(cells), cells[row][col]
for dr, dc in DIRECTIONS:
count = 1
for sign in (1, -1): # walk both ways along the line
r, c = row + sign * dr, col + sign * dc
while 0 <= r < n and 0 <= c < n and cells[r][c] == player:
count += 1
r, c = r + sign * dr, c + sign * dc
if count >= k:
return True
return False
That is O(K) per move. The nice part is that the change stays inside one class: we make the win rule an interface (WinRule.record(row, col, player) -> bool), keep WinTracker as the full-line rule and add a KInARowRule that reads the board. TicTacToe does not change. This same "walk out from the last move" check is the heart of /low-level-design/connect-four.
2) How would you add a computer player?
Now "player" has behavior: a human waits for input, a computer picks a cell. This is the point where a Player abstraction earns its place, as a Strategy for choosing moves.
class Player:
def choose_move(self, game: "TicTacToe") -> Tuple[int, int]:
raise NotImplementedError
class RandomPlayer(Player):
def __init__(self, rng: random.Random):
self.rng = rng
def choose_move(self, game: "TicTacToe") -> Tuple[int, int]:
free = game.board.empty_cells()
return self.rng.choice(free)
def play(game: TicTacToe, players: Dict[int, Player]) -> int:
while game.current_player() != 0:
row, col = players[game.current_player()].choose_move(game)
game.move(row, col, game.current_player())
return game.status.value
The game class still only validates and applies moves; the loop that asks players for moves lives outside it. A stronger computer player (one that blocks your winning line, or a full minimax search on 3 by 3) is just another Player subclass. Minimax needs to try a move and take it back, which leads straight into the next question. See /low-level-design/strategy-pattern for the pattern itself.
3) How would you add undo?
Keep a stack of moves. Undo pops the last one and reverses everything move did. The counter design makes this cheap: subtracting the same delta from the same four counters restores them exactly.
@dataclass
class Move:
row: int
col: int
player: int
def undo(self) -> bool:
if not self.history:
return False
last = self.history.pop()
self.board.clear(last.row, last.col)
self.wins.unrecord(last.row, last.col, last.player) # the same updates with -delta
self.turn = last.player # it is their turn again
self.status = Status.IN_PROGRESS
return True
move gains one line (self.history.append(Move(row, col, player))) after a successful move. If undo must also be redone, or moves need to be replayed for a spectator, each Move can become a command object with apply and revert methods. That is the Command pattern, and it is only worth it when there are several kinds of action to undo. For one kind of move, a plain stack of records is enough.
4) How would you host many games at once on a server?
Each game is already a self-contained object, so a server keeps a map from game id to game, and a lock per game so two requests for the same game cannot interleave.
class GameService:
def __init__(self):
self.games: Dict[str, TicTacToe] = {}
self.locks: Dict[str, threading.Lock] = {}
def create(self, game_id: str, n: int) -> None:
self.games[game_id] = TicTacToe(n)
self.locks[game_id] = threading.Lock()
def move(self, game_id: str, row: int, col: int, player: int) -> int:
with self.locks[game_id]:
return self.games[game_id].move(row, col, player)
Without the lock, two quick clicks from the same player could both pass the player != self.turn check before either updates turn, which is a classic check-then-act race. One lock per game is enough because games never touch each other. The map itself also needs protection if games are created while others are running (one service-level lock around create, or a concurrent map). Persisting a game is easy too: the board, the turn and the status are the whole state, and the counters can be rebuilt by replaying the cells. See /low-level-design/race-conditions-and-locks.
💡 Interview tip: For every follow-up, say first which class changes and which do not. "Only the win rule changes;
TicTacToeandBoardstay the same" is the sentence that shows your boundaries were drawn in the right places.
What is Expected at Each Level?
Junior
A junior candidate should model the board and the game, write a move method that places marks and alternates turns, and detect a winner, even with a full-board scan. With a hint they should reject taken cells and moves off the board, handle the draw, and trace a short game by hand. Mixing the win check into move is fine at this level as long as it is correct.
Mid-level
A mid-level candidate asks about the board size, turn rules and what an illegal move should return before coding. They keep validation ahead of any state change, check only the lines through the last move without being told, and catch the subtle cases: a win on the last cell is not a draw, and the center of an odd board is on both diagonals. They can explain the cost of each method and why Player and Cell are not classes.
Senior
A senior candidate gets to the O(1) running-counter check and explains in one sentence why a sum of N proves a full line. They are just as clear about its limit: the trick only works when a win means a whole line, so K in a row needs a different rule behind the same interface. On follow-ups they introduce abstractions only when a requirement calls for them (a Player strategy for computer opponents, a move stack for undo, a lock per game for a server) and say why each one was not needed before.