Design tic-tac-toe: an N-by-N game with win detection
I was asked this
No reports yet. Sign in to say where you were asked it.
Design an N-by-N tic-tac-toe game for two players in code. Players take turns placing their mark; a player wins by filling a whole row, column or either diagonal. After each move the game must say whether that move won, drew or neither, and that check should be O(1), not a scan of the board.
Requirements
- Functional: create a game with board size
n;move(row, col)places the current player's mark and returns the result (in progress, X wins, O wins, draw); reject moves out of range, on a taken cell, or after the game ended; turns alternate. - Non-functional: checking a win after a move is O(1); the classes make it easy to change the win rule or add a computer player.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
Game(n: int);move(row: int, col: int) -> strreturns"in_progress","X_wins","O_wins"or"draw".
g = Game(3)
g.move(0, 0) -> "in_progress" # X
g.move(1, 1) -> "in_progress" # O
g.move(0, 1) -> "in_progress" # X
g.move(2, 2) -> "in_progress" # O
g.move(0, 2) -> "X_wins" # top row
Clarifying questions
- Does a player need
nin a row, orkin a row on a larger board? - Who goes first, and can players choose their marks?
- Should the game report a draw as soon as no one can win, or only when the board is full?
- Is undo needed?
- Is a computer opponent in scope?
What a strong answer covers
- Core classes:
Game(board, players, current turn, status),Board(cells,place,is_full),Player(mark, and aMoveStrategyfor human or computer), andWinChecker. - O(1) win detection: counters per row, per column and for the two diagonals, +1 for X and -1 for O; a counter reaching
nor-nmeans a win. - Draw when the move count reaches
n * nwithout a win. - Validation and clear errors for illegal moves, and the game status as a small state machine.
- Tests: wins on a row, a column and both diagonals, a draw, a move after the game ended.
Follow-ups
- Change the rule to
kin a row on anm x nboard. Why do the counters no longer work, and what replaces them? - Add a computer player that never loses on a 3x3 board.
- Add undo.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.


