0. Problem overview
Design an object-oriented Tic-Tac-Toe game.
Two players take turns placing their respective symbols on a board. A player wins by completing a winning line. In standard Tic-Tac-Toe, the board is 3×3 and a player wins by completing:
- A horizontal row.
- A vertical column.
- The main diagonal.
- The anti-diagonal.
If every cell is occupied and neither player has won, the game ends in a draw.
The core problem looks simple, but it tests several important LLD concepts:
- Object modelling and responsibility assignment.
- Encapsulation and invariants.
- Game lifecycle and state transitions.
- Move validation and turn management.
- Algorithm design and optimization.
- Strategy pattern and extensibility.
- Concurrency and atomic state changes.
- Testing and edge-case handling.
- Separating a simple machine-coding problem from a larger online game product.
1. Understand the different versions of the problem
One important lesson from the supplied references is that they do not all solve exactly the same problem.
There are four major variants.
Variant A: Basic machine-coding Tic-Tac-Toe
- Two human players.
- 3×3 board.
- X starts.
- Players alternate turns.
- Invalid moves are rejected.
- Winner and draw are detected.
- Console input/output.
This is the most common machine-coding baseline.
Variant B: Configurable-board Tic-Tac-Toe
- Board size is configurable: N×N.
- Players may still be human vs human.
- Win condition may be an entire row, column, or diagonal.
- Game logic should not hardcode 3.
This tests extensibility and algorithm design.
Variant C: AI-enabled Tic-Tac-Toe
- Human vs computer.
- Different AI strategies.
- Random or minimax-based move selection.
- Game engine remains independent of how a player chooses a move.
This tests the Strategy pattern and separation of decision-making from game execution.
Variant D: Online multiplayer Tic-Tac-Toe
- Players register or authenticate.
- Players create and join games.
- Multiple games run simultaneously.
- Moves arrive through APIs.
- Concurrent requests must be handled correctly.
- Game state may be persisted.
- Clients may reconnect or retry requests.
- Opponents may receive real-time notifications.
This tests concurrency, consistency, API design, and lifecycle management.
Interview recommendation: Start with Variant A unless the interviewer explicitly asks for something larger. Discuss B, C, and D as extensions.
Do not build an online game platform when the question asks for a command-line game.
2. Requirement gathering
Before creating classes, clarify requirements.
2.1 Questions to ask
| Question | Baseline assumption |
|---|---|
| Board size? | 3×3 |
| Number of players? | Exactly two |
| Player types? | Human vs human |
| Who starts? | X |
| Symbols? | X and O |
| Win condition? | Complete row, column, or diagonal |
| Can a player overwrite a cell? | No |
| What happens on invalid move? | Reject it; same player retries |
| What happens after a win? | Game ends immediately |
| What happens when board is full? | Draw if there is no winner |
| Undo? | Not required initially |
| AI? | Not required initially |
| Multiple games? | Not required initially |
| Persistent history? | Not required initially |
| Concurrent requests? | Discuss if online multiplayer is in scope |
2.2 Functional requirements
- Create a game.
- Initialize an empty board.
- Create two players.
- Assign a unique symbol to each player.
- Start the game.
- Track the current player.
- Accept a move from the current player.
- Validate player identity and move position.
- Reject moves on occupied cells.
- Update the board after a valid move.
- Detect a winner.
- Detect a draw.
- Switch turns when the game continues.
- Prevent moves after the game ends.
- Display the board and result.
2.3 Non-functional requirements
- Correctness.
- Encapsulation.
- Maintainability.
- Extensibility.
- Testability.
- Clear separation of concerns.
- Thread safety if concurrent access is supported.
- Low-latency move processing for an online game.
2.4 Explicit out-of-scope decisions
For the baseline:
- No user registration.
- No database.
- No distributed infrastructure.
- No tournament management.
- No leaderboard.
- No network multiplayer.
- No AI.
- No undo/redo.
These can be added later without changing the core rules.
3. Identify the domain entities
The key is to identify objects with distinct responsibilities.
Do not create a class for every noun. A class should have a meaningful role.
3.1 Core entities
| Entity | Responsibility |
|---|---|
| Player | Represents a participant |
| Board | Owns the grid and cell state |
| Cell | Represents one board position, if modelled explicitly |
| Game | Coordinates turns, moves, rules, and lifecycle |
| Move | Records a committed move |
| Position | Represents row and column |
| GameResult | Represents the final outcome |
| WinStrategy | Determines whether a move wins |
| PlayerStrategy | Chooses a move for a computer player |
The minimum viable implementation can use only:
- Player
- Board
- Game
- Symbol enum
- GameStatus enum
- MoveResult
The other abstractions are useful when requirements justify them.
4. Detailed domain model
4.1 Symbol
Possible values:
Symbol:
X
O
EMPTYWhy use an enum?
- Prevents arbitrary symbols.
- Makes comparisons type-safe.
- Makes the set of possible values explicit.
- Avoids string and character inconsistencies.
Do not represent empty cells using an arbitrary player symbol.
4.2 Player
Attributes:
Player:
playerId
name
symbol
typeWhere:
- playerId: unique identity.
- name: display name.
- symbol: X or O.
- type: HUMAN or COMPUTER, if needed.
Responsibilities:
- Represent player identity.
- Hold the symbol assigned to the player.
- Optionally hold a PlayerStrategy.
Design decisions:
- Player identity and assigned symbol should be immutable during a game.
- A player must not have EMPTY as its symbol.
- Two players must not share the same symbol.
- Player name should not be used as unique identity.
Should Player contain the makeMove method?
There are two reasonable approaches:
Approach 1: Player is primarily data
Player contains identity and symbol. Game accepts a move request from the player.
This is simple and recommended for basic LLD.
Approach 2: Player owns a move-selection strategy
A human or computer player can delegate move selection to a PlayerStrategy.
This is useful for AI extensions.
Do not make Player directly mutate the Board. The Game must validate and authorize every move.
4.3 Cell
Attributes:
Cell:
row
column
symbolResponsibilities:
- Hold the symbol at that position.
- Report whether the cell is empty.
A Cell does not decide whose turn it is or whether someone has won.
Is Cell necessary?
No.
A 2D array of Symbol is sufficient for a simple game.
Use a Cell class when cells need additional behaviour or metadata, such as:
- Highlighting winning cells.
- Display state.
- Special cell rules.
- Coordinates and cell-level behaviour.
Avoid adding Cell merely to increase the number of classes.
4.4 Board
Attributes:
Board:
size
cells
occupiedCountResponsibilities:
- Initialize the grid.
- Validate positions.
- Check whether a cell is empty.
- Place a symbol.
- Check whether the board is full.
- Return a board snapshot.
- Expose cell values through controlled methods.
Important:
Board should not manage:
- Current player.
- Player identity.
- Game status.
- Winner.
- Turn switching.
These belong to Game.
The grid must be private. Do not expose the mutable internal array.
4.5 Move
Attributes:
Move:
moveNumber
playerId
symbol
position
timestampResponsibilities:
- Represent a committed move.
- Support history.
- Support replay.
- Support undo.
- Help with debugging and auditing.
A Move should generally be immutable after creation.
Only successful moves should be recorded in move history.
4.6 Position
Position:
row
columnA Position is a small value object.
It avoids passing unrelated integer parameters everywhere.
For example:
makeMove(playerId, Position)is more expressive than:
makeMove(playerId, row, column)Both are acceptable in a machine-coding interview.
4.7 GameStatus
Possible values:
GameStatus:
NOT_STARTED
IN_PROGRESS
WON
DRAW
ABORTEDTerminal states:
- WON
- DRAW
- ABORTED
For the simplest implementation, IN_PROGRESS, WON, and DRAW are enough.
Use a separate winner field rather than encoding WINNER_X and WINNER_O into the status when player identity and symbols are already available.
Example:
Game:
status = WON
winner = Player XThis generalizes better if symbols or player identities change.
4.8 GameResult
Attributes:
GameResult:
status
winner
winningLineThe winning line is optional, but useful for UI highlighting.
4.9 Game
Attributes:
Game:
gameId
board
players
currentPlayerIndex
status
winner
moveHistory
winStrategyResponsibilities:
- Start the game.
- Track the current player.
- Validate player identity and turn.
- Validate the move.
- Apply a valid move.
- Record the move.
- Determine win or draw.
- Switch turns.
- Prevent moves after termination.
- Return the result.
Game is the orchestrator.
The Board owns cell state. Game owns the rules and lifecycle.
5. Recommended class diagram
Relationships
- Game has a Board: composition.
- Game references Players: association or aggregation.
- Board owns the grid.
- Game owns the move history for the match.
- Game depends on WinStrategy through an interface.
- Move references Position.
A GameManager is not necessary for a single game.
6. Application architecture
Keep the presentation layer separate from game rules.
| Component | Responsibility |
|---|---|
| UI | Collect player input and display output |
| Controller | Translate input into game commands |
| Game | Enforce game rules |
| Board | Own grid state |
| WinStrategy | Detect winning lines |
| Move history | Store successful moves |
The controller should not independently decide:
- Whose turn it is.
- Whether a move is legal.
- Whether a player has won.
- Whether the game has ended.
These are domain responsibilities.
7. Core game workflow
The most important method is:
makeMove(playerId, position) -> MoveResultThe move must be processed in this order:
- Check whether the game is in progress.
- Check whether the player belongs to the game.
- Check whether it is that player's turn.
- Validate the coordinates.
- Check whether the cell is empty.
- Place the symbol.
- Record the move.
- Check for a win.
- If no win, check for a draw.
- If neither, switch turns.
- Return the updated result.
Invariant: An invalid move must not change any game state.
This means it must not change:
- Board.
- Occupied count.
- Current player.
- Move history.
- Game status.
- Winner.
- Win-tracking counters.
7.1 Sequence diagram
7.2 Why check winner before draw?
The final cell can complete a winning line.
If the implementation checks whether the board is full before checking the win, it may incorrectly declare a draw.
Correct order:
place move
if winning move:
status = WON
winner = current player
else if board is full:
status = DRAW
else:
switch player7.3 Why switch only after a successful non-terminal move?
If a player selects an occupied cell, they must retry.
If the game has ended, there is no next player.
Turn switching must happen only after a valid move that does not end the game.
8. Game lifecycle and state transitions
Important rules:
- A new game starts in NOT_STARTED or IN_PROGRESS, depending on the API.
- A valid non-terminal move leaves the game in progress.
- A winning move transitions to WON.
- A full board without a winner transitions to DRAW.
- Terminal states cannot accept further moves.
- A restart should create a new match or perform an explicit reset.
Enum vs State pattern
For Tic-Tac-Toe, use an enum.
A separate State pattern is usually unnecessary because the lifecycle has very little state-specific behaviour.
Use the State pattern only when state-specific behaviour becomes sufficiently complex.
The State pattern does not provide thread safety.
9. Win detection algorithms
This is one of the most important technical parts of the problem.
There are several approaches. Choose according to the board rules.
9.1 Approach 1: Full board scan
After every move:
- Scan all rows.
- Scan all columns.
- Scan main diagonal.
- Scan anti-diagonal.
For an N×N board:
- Row scan: O(N²).
- Column scan: O(N²).
- Diagonal scan: O(N).
Total: O(N²).
Advantages:
- Very simple.
- Easy to understand.
- Easy to test.
- Suitable for a small 3×3 board.
Disadvantages:
- Rechecks unrelated lines.
- Does more work than necessary.
Correctness warning:
Never treat a line of EMPTY cells as a winning line.
A correct line check must first verify that the candidate symbol is not EMPTY.
Example:
first = board[row][0]
if first == EMPTY:
return false
for col from 1 to N-1:
if board[row][col] != first:
return false
return trueThe same principle applies to columns and diagonals.
9.2 Approach 2: Check only the affected lines
After a move at (r, c), only four lines can have become winning lines:
- Row r.
- Column c.
- Main diagonal, if r == c.
- Anti-diagonal, if r + c == N - 1.
Why?
Only one cell changed. Any line not containing that cell was unchanged by the move. A legal game would already have ended if such a line had been complete.
For each relevant line, count matching symbols.
For an N×N board with a requirement to fill the complete line, complexity is O(N) per move.
This is an excellent baseline algorithm.
9.3 Approach 3: Per-player row and column counters
This is the optimization discussed in LeetCode 348, Algo Monster, and Educative.
Assumption:
- Board is N×N.
- A player wins by filling an entire row, column, or diagonal.
- Moves are valid.
- Player identity is known.
- No duplicate or occupied-cell validation is required by the narrow algorithmic problem.
Maintain separate counters for each player:
rowCount[player][N]
columnCount[player][N]
mainDiagonalCount[player]
antiDiagonalCount[player]On a move at (r, c):
rowCount[player][r] += 1
columnCount[player][c] += 1
if r == c:
mainDiagonalCount[player] += 1
if r + c == N - 1:
antiDiagonalCount[player] += 1
if rowCount[player][r] == N:
winner = player
if columnCount[player][c] == N:
winner = player
if mainDiagonalCount[player] == N:
winner = player
if antiDiagonalCount[player] == N:
winner = playerEach move checks at most four counters.
Time complexity: O(1) per move.
Space complexity: O(N) per player.
Why separate counters work
Each player's counters count only their own marks.
If a row contains:
X X OX's count is 2, not 3.
O's count is 1.
If a row contains:
X X XX's count is 3, which equals N.
Important limitation
This algorithm does not itself validate:
- Whether a cell is occupied.
- Whether the player is allowed to move.
- Whether the game is over.
- Whether the move is within bounds.
Those checks are omitted in the narrow LeetCode problem because valid moves are guaranteed.
In a full LLD solution, validate the move before updating counters.
9.4 Approach 4: Signed counters
An alternative uses one counter per row and column:
- X contributes +1.
- O contributes -1.
Example:
X X OTotal = +1.
If all cells are X, total = +N.
If all cells are O, total = -N.
A win occurs when the absolute value equals N.
This can reduce counter storage.
However, it assumes exactly two players and two distinct symbols.
Separate per-player counters are easier to generalize to more players.
9.5 Approach 5: Generalized K-in-a-row
Now suppose:
- Board is 15×15.
- Win length is 5.
- Five consecutive symbols anywhere in the board win.
A player does not need to fill an entire row or column.
Use directional scanning from the last move.
Directions:
Horizontal: (0, 1)
Vertical: (1, 0)
Main diagonal: (1, 1)
Anti-diagonal: (1, -1)For each direction:
total = 1 + countForward + countBackward
if total >= K:
winner = current playerThe initial 1 represents the newly placed cell.
For fixed K, this is O(K) per move.
This is not the same problem as whole-row N-in-a-row.
9.6 Algorithm comparison
| Scenario | Recommended approach | Complexity per move |
|---|---|---|
| Simple 3×3 | Full scan or affected-line scan | O(1) for fixed 3 |
| N×N, complete line required | Affected-line scan | O(N) |
| N×N, complete line required | Per-player counters | O(1) |
| Larger board, K consecutive marks | Directional scan | O(K) |
| Very small board, easiest implementation | Full scan | O(N²) |
Interview recommendation
Start with affected-line checking because it is intuitive and easy to prove correct.
Then explain per-player counters as an optimization.
Discuss K-in-a-row separately so you do not incorrectly apply the counter algorithm to a different winning rule.
10. Board representation trade-offs
10.1 Two-dimensional array
[
[X, O, EMPTY],
[EMPTY, X, O],
[O, EMPTY, X]
]Advantages:
- Natural mapping to rows and columns.
- Easy display.
- Simple validation.
- Easy to understand.
Best choice for standard Tic-Tac-Toe.
10.2 One-dimensional array
Store N² cells in one array.
Formula:
index = row * N + columnReverse:
row = index / N
column = index % NUseful for flattened representations and serialization, but less readable.
10.3 Enum vs PlayingPiece classes
Two common designs appear in the references.
Design A: Enum-based
Symbol:
X
O
EMPTYBoard:
Symbol[][] cellsAdvantages:
- Simple.
- Type-safe.
- Minimal classes.
- Appropriate for fixed symbols.
Design B: Polymorphic PlayingPiece
PlayingPiece
PlayingPieceX
PlayingPieceOBoard:
PlayingPiece[][] cellsAdvantages:
- Supports different piece behaviour if pieces genuinely vary.
- Demonstrates polymorphism.
- Can be useful for a family of game pieces.
Disadvantages:
- More classes.
- Often no real behaviour variation in Tic-Tac-Toe.
- May be unnecessary abstraction.
Recommendation:
Use an enum for standard Tic-Tac-Toe. Use PlayingPiece subclasses only when the pieces have different behaviour, not merely different labels.
11. API and method design
11.1 Core APIs
start()
makeMove(playerId, position)
getCurrentPlayer()
getBoardSnapshot()
getStatus()
getResult()
getMoveHistory()
abort()Most important:
makeMove(playerId, position) -> MoveResultMoveResult should include:
success
errorCode
gameStatus
nextPlayer
winner
winningLine
boardSnapshotError codes might include:
INVALID_PLAYER
NOT_YOUR_TURN
OUT_OF_BOUNDS
CELL_OCCUPIED
GAME_NOT_STARTED
GAME_OVER11.2 Online REST APIs
POST /games
GET /games/{gameId}
POST /games/{gameId}/moves
GET /games/{gameId}/moves
POST /games/{gameId}/abort
POST /games/{gameId}/rematchExample move request:
{
"row": 0,
"column": 2
}The authenticated user identity should come from the server's authentication context.
Do not trust a client-provided player ID to establish who is making the move.
12. Concurrency and thread safety
For a local console game, concurrency is not usually necessary.
For an online game, two players may send requests simultaneously.
12.1 Race condition example
It is X's turn.
Two requests arrive at nearly the same time.
Both threads:
- Read currentPlayer = X.
- Validate the move.
- Place X.
- Advance the turn.
Both moves may be marked X.
This corrupts the game.
12.2 Protect the complete move transition
The critical section includes:
- Game status check.
- Player identity check.
- Turn check.
- Position validation.
- Occupancy validation.
- Board update.
- Counter update.
- Move history update.
- Win/draw check.
- Turn update.
Do not lock only the board write.
The game state must transition atomically.
12.3 Per-game lock
Use one lock per Game instance.
Why per-game?
A global lock would make unrelated games block each other.
A per-cell lock is insufficient because turn and game status are shared state.
12.4 Optimistic concurrency
For a database-backed game, store:
Game:
gameId
currentPlayer
status
versionA client or server operation uses the expected version.
The database updates only if the version matches.
Conceptual SQL:
UPDATE game
SET version = version + 1
WHERE game_id = :game_id
AND version = :expected_version;The board update, move record, and game transition must be part of the same transaction or equivalent atomic commit.
If no row is updated, another request won the race or the version is stale.
12.5 Local lock vs distributed coordination
A mutex or synchronized method protects one process only.
If multiple server instances handle the same game, local locks are insufficient.
Possible approaches:
- Route one game to a single authoritative server.
- Use database transactions and conditional updates.
- Use a distributed lock if necessary.
For a small game, database optimistic concurrency is often easier to reason about than distributed locking.
12.6 Idempotency and duplicate requests
A client may retry a move after a network timeout even though the first request succeeded.
Use an idempotency key:
makeMove(gameId, requestId, playerId, position)Store the result associated with the request ID.
- First request: process and store result.
- Duplicate with same payload: return stored result.
- Same request ID with different payload: reject.
This is an online-game concern, not a necessary console-game feature.
13. Design patterns
Use patterns where they solve actual variation.
13.1 Strategy pattern
Two separate strategies may exist.
PlayerStrategy
Determines which move a player wants to make.
interface PlayerStrategy:
chooseMove(board, player) -> PositionImplementations:
- HumanStrategy.
- RandomStrategy.
- MinimaxStrategy.
WinStrategy
Determines whether a move has created a winning condition.
interface WinStrategy:
checkWinner(board, lastMove) -> resultImplementations:
- StandardThreeInARowStrategy.
- ConfigurableKInARowStrategy.
These are different responsibilities.
13.2 Observer pattern
Useful when several components react to game events:
- Scoreboard.
- Game history.
- Analytics.
- Notifications.
Example event:
GameEnded:
gameId
winner
resultThe core game should not synchronously wait for email or analytics.
For a local game, direct calls or a simple listener list are enough.
13.3 Factory pattern
A factory may create:
- Human player.
- Computer player.
- Different game configurations.
Use it if player creation has real complexity.
Do not create a factory just to instantiate one simple Player constructor.
13.4 State pattern
Not required for the basic lifecycle.
An enum is sufficient.
Use State objects only if behaviour varies significantly by lifecycle state.
13.5 Command pattern
A Move can be represented as a command.
Useful for:
- Undo.
- Redo.
- Replay.
- Auditing.
- Network command processing.
For the baseline, an immutable Move record is sufficient.
13.6 Memento pattern
Can capture and restore game state.
For a small game, move history and reverse operations are often simpler.
13.7 Pattern summary
| Pattern | Recommendation |
|---|---|
| Strategy | Useful for AI and configurable win rules |
| Observer | Optional for game events |
| Factory | Optional for multiple player types/configurations |
| State | Usually unnecessary |
| Command | Optional for undo/replay |
| Memento | Optional for snapshots |
| Repository | Only if persistence is required |
| Singleton | Avoid |
| Facade | Usually unnecessary |
14. SOLID principles
| Principle | Application |
|---|---|
| Single Responsibility | Board owns cells; Game owns turn and lifecycle |
| Open/Closed | Add new win strategies without rewriting Game |
| Liskov Substitution | Every WinStrategy must honour the same contract |
| Interface Segregation | Keep PlayerStrategy and WinStrategy separate |
| Dependency Inversion | Game depends on WinStrategy abstraction |
Additional principles:
- Encapsulation: hide mutable board state.
- Composition over inheritance: Game has a Board.
- KISS: choose the simplest correct design.
- YAGNI: do not implement unrequested features.
15. Extensions
15.1 Configurable board size
Use:
Board(size)Do not hardcode 3 in loops or validation.
Separate board size N from win length K if the game supports K-in-a-row.
15.2 AI opponent
AI is a player with a PlayerStrategy.
Random strategy
- Find empty cells.
- Select one randomly.
- Return the position.
Minimax strategy
Minimax is an algorithm for two-player zero-sum games.
It assumes both players make optimal moves.
Example scoring:
AI win +10
AI loss -10
Draw 0Algorithm:
- Generate legal moves.
- Simulate a candidate move.
- Evaluate terminal states.
- Recursively evaluate opponent responses.
- Maximize AI score.
- Minimize opponent score.
- Select the best move.
For 3×3, exhaustive minimax is feasible.
For larger games, use:
- Alpha-beta pruning.
- Move ordering.
- Depth limits.
- Heuristic evaluation.
Alpha-beta pruning skips branches that cannot affect the final minimax choice.
15.3 Undo and redo
Store every successful move.
Undo must:
- Remove the last move from history.
- Clear the corresponding board cell.
- Decrease occupied count.
- Restore the previous player.
- Restore game status.
- Restore winner information.
- Restore or recompute win counters.
Important: Clearing a board cell alone is not enough.
The derived state must also be restored.
For a small board, recomputing the game status and counters from the remaining history is often safer than manually reversing every derived value.
For online competitive play, define whether undo is allowed and whether both players must approve.
15.4 Replay
- Create a new game with the same configuration.
- Apply recorded moves in order.
- Validate each move.
- Reconstruct the board and final result.
Move history makes this straightforward.
15.5 Scoreboard and tournament manager
Introduce a GameManager or TournamentManager only if multiple games are required.
Possible responsibilities:
- Create games.
- Find games by ID.
- Track active games.
- Start rematches.
- Track player statistics.
- Maintain tournament standings.
Scoreboard should not be owned by an individual Game.
15.6 Multiple players
This is not simply changing a two-element player list.
Clarify:
- How many symbols?
- What is the turn order?
- What is a win?
- Can multiple winners exist?
- What is a draw?
The signed +1/-1 counter technique does not generalize directly to arbitrary player counts.
15.7 Online multiplayer
Additional components:
- Authentication.
- Game creation and joining.
- Game repository.
- Move API.
- Persistent state.
- Concurrency control.
- Reconnection.
- Idempotency.
- Real-time notifications.
- Timeout and abandonment policy.
The server remains authoritative.
The client can optimistically display a move, but the server decides whether it is legal.
16. Online multiplayer architecture
This is an extension, not the baseline machine-coding design.
Component responsibilities
| Component | Responsibility |
|---|---|
| Authentication | Identify caller |
| Game Service | Create, join, fetch, and manage games |
| Game Engine | Validate and apply moves |
| Game Repository | Load and persist state |
| Database | Store game, player, and move records |
| Event Publisher | Publish committed game events |
| Notification Service | Notify players of moves and results |
Possible persistence model
Game:
gameId
status
currentPlayerId
boardState
version
createdAt
updatedAt
GamePlayer:
gameId
playerId
symbol
Move:
moveId
gameId
moveNumber
playerId
row
column
createdAtUseful constraints:
- Unique (gameId, moveNumber).
- Unique (gameId, row, column).
- Version check on game updates.
The database must enforce the critical invariants as well as the application.
17. Important invariants
An invariant is a condition that must always remain true in a valid game.
For standard Tic-Tac-Toe:
- A cell contains only X, O, or EMPTY.
- A cell can be occupied only once.
- X and O are assigned to different players.
- X starts.
- X count equals O count or is exactly one greater.
- Only the current player may move.
- A successful move increases occupied count by one.
- A rejected move changes no game state.
- A terminal game cannot accept moves.
- An IN_PROGRESS game has no winning line.
- An IN_PROGRESS game is not full.
- The move history must agree with the board.
- The occupied count must agree with the number of non-empty cells.
For a valid completed game, the move history should not contain moves after the first winning move.
These invariants are excellent candidates for assertions and tests.
18. Edge cases and failure handling
| Scenario | Expected behaviour |
|---|---|
| Negative row | Reject |
| Negative column | Reject |
| Row >= board size | Reject |
| Column >= board size | Reject |
| Occupied cell | Reject |
| Wrong player | Reject |
| Player not in game | Reject |
| Move after win | Reject |
| Move after draw | Reject |
| Invalid move | Same player retries |
| Final move wins | Declare win, not draw |
| Final move does not win | Declare draw |
| Aborted game | Reject subsequent moves |
| Concurrent requests | At most one legal transition commits |
| Duplicate online retry | Return original result if idempotency is supported |
| Read during move | Return a consistent snapshot |
19. Testing strategy
19.1 Unit tests
| Test | Expected result |
|---|---|
| Empty board creation | All cells EMPTY |
| Game creation | Correct players and board |
| First move | X placed |
| Second move | O placed |
| Horizontal win | Winner detected |
| Vertical win | Winner detected |
| Main diagonal win | Winner detected |
| Anti-diagonal win | Winner detected |
| Draw | DRAW |
| Occupied cell | Rejected |
| Out-of-bounds | Rejected |
| Wrong player | Rejected |
| Move after win | Rejected |
| Move after draw | Rejected |
| Invalid move | No state mutation |
19.2 Concurrency tests
- Two requests try to play the same cell.
- Two requests try to move during the same turn.
- Two requests submit moves for different players simultaneously.
- Two requests race to fill the last cell.
- Same request is retried with the same idempotency key.
Verify:
- Only valid moves commit.
- Board and move history agree.
- Turn is correct.
- No moves occur after terminal state.
- No duplicate move is applied.
19.3 Property-based tests
Generate random legal and invalid sequences.
Verify invariants after every operation.
Examples:
- Occupied count never exceeds N².
- Every successful move increments count once.
- Invalid move does not change state.
- Terminal state remains terminal.
- Winner has a valid winning line.
20. Complexity analysis
Let N be the board dimension.
| Operation | Complexity |
|---|---|
| Initialize board | O(N²) |
| Validate coordinates | O(1) |
| Check cell availability | O(1) |
| Place symbol | O(1) |
| Check full board with occupied count | O(1) |
| Check full board by scanning | O(N²) |
| Full win scan | O(N²) |
| Affected-line win scan | O(N) |
| Counter-based win detection | O(1) |
| K-in-a-row directional scan | O(K) |
| Board storage | O(N²) |
| Per-player row/column counters | O(N) |
For standard 3×3, the simpler scan is perfectly adequate.
For larger boards, counters may be worthwhile if the rules match their assumptions.
21. Common mistakes
| Mistake | Why it is wrong | Better approach |
|---|---|---|
| Board as Singleton | Prevents multiple independent games | Each Game owns its Board |
| UI inside Game | Couples domain to presentation | Separate controller |
| Direct external board mutation | Bypasses validation | Mutate through Game |
| No player identity validation | Allows impersonation in online play | Validate authenticated player |
| Check draw before win | Final move may win | Check win first |
| Switch after invalid move | Wrong turn semantics | Switch only after valid non-terminal move |
| Accept moves after game over | Breaks lifecycle invariant | Check status first |
| Empty line treated as win | Incorrect scan logic | Reject EMPTY candidate |
| Scan every line unnecessarily | Wastes work | Check affected lines |
| Use whole-line counters for K-in-a-row | Does not detect arbitrary contiguous runs | Directional scan |
| Lock only board write | Turn/status/history can race | Lock complete transition |
| One global lock | Unrelated games block | Per-game lock |
| Expose mutable array | External corruption | Snapshot/read-only view |
| Overuse inheritance | Unnecessary complexity | Enum for simple symbols |
| Too many patterns | Overengineering | Add only justified abstractions |
| AI logic in Game | Couples decisions to rules | PlayerStrategy |
| Undo clears only cell | Other derived state remains stale | Restore or recompute all state |
22. How to implement in a machine-coding interview
22.1 Recommended order
- Symbol enum.
- GameStatus enum.
- Player.
- Board.
- Game.
- MoveResult.
- Win detection.
- Driver / console interaction.
- Tests.
22.2 Minimum viable class set
| Class | Responsibility |
|---|---|
| Player | Identity and symbol |
| Board | Grid and cell operations |
| Game | Turns, validation, lifecycle |
| MoveResult | Result of a move |
| Symbol | X, O, EMPTY |
| GameStatus | IN_PROGRESS, WON, DRAW |
Add strategy and history only when requirements call for them.
22.3 Suggested 45–60 minute interview allocation
| Time | Activity |
|---|---|
| 0–5 min | Clarify requirements |
| 5–10 min | Define scope and assumptions |
| 10–15 min | Identify entities |
| 15–22 min | Draw class diagram |
| 22–32 min | Implement board and move flow |
| 32–38 min | Implement win/draw detection |
| 38–43 min | Handle invalid moves and lifecycle |
| 43–48 min | Explain concurrency |
| 48–55 min | Discuss AI, undo, N×N, online game |
| 55–60 min | Test and summarize trade-offs |
23. Interview follow-up questions
Object modelling
- Why is Board separate from Game?
- Why should Board not manage the current player?
- Do we need a Cell class?
- Should we use enum or PlayingPiece subclasses?
- Why should Board not be a Singleton?
- What should Move contain?
- Should Game own Player objects or reference them?
Algorithms
- How do you detect a winner?
- Why can you check only the last move's row, column, and diagonals?
- How do you optimize winner detection to O(1)?
- Why do counter-based algorithms work?
- Why do they not solve arbitrary K-in-a-row?
- How do you detect K consecutive marks?
- How do you detect a draw efficiently?
State and correctness
- What happens if a player selects an occupied cell?
- Why check win before draw?
- Why switch turn only after a successful move?
- How do you prevent moves after a game ends?
- What invariants should always hold?
Design patterns
- Where would you use Strategy?
- Why separate PlayerStrategy from WinStrategy?
- Is State pattern necessary?
- Where can Observer be useful?
- How would Command help undo?
- Would you use Factory?
Concurrency
- What happens if both players submit moves simultaneously?
- Why is locking only the Board insufficient?
- Why use a per-game lock?
- How would multiple application instances coordinate?
- How would optimistic locking work?
- How would you handle duplicate requests?
Extensions
- How do you add AI?
- How does minimax work?
- How do you support configurable board size?
- How do you support K-in-a-row?
- How do you implement undo?
- How do you implement replay?
- How do you support multiple games?
- How would you build an online multiplayer version?
24. Recommended final interview design
For the standard machine-coding question, present:
Player
Board
Game
Symbol
GameStatus
MoveResultUse:
- A private 2D array of Symbol.
- Game as the sole orchestrator of valid moves.
- Board for grid operations.
- Explicit player identity and turn validation.
- A clear game lifecycle.
- Affected-line winner detection.
- Win check before draw check.
- Turn switch only after valid non-terminal moves.
- Per-game locking if concurrent access is in scope.
Then explain extensions:
WinStrategy
PlayerStrategy
MoveHistory
GameManager
GameRepositoryDo not implement these all up front.
The most important lessons
- Model responsibilities, not just nouns.
- Keep Board and Game separate.
- Keep UI separate from domain logic.
- Make invalid moves side-effect free.
- Understand the difference between whole-line and K-in-a-row rules.
- Understand both affected-line scanning and counter-based optimization.
- Protect the complete game transition under concurrency.
- Use Strategy for genuinely variable behaviour.
- Treat undo as reversal of all state, not just the board cell.
- Separate local machine coding from online multiplayer architecture.
- Prefer simple, correct design over unnecessary abstractions.
- Be able to explain why each class exists and what would change if a requirement were added.