logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramlinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Atomic CASGlobal Lock OrderingRead Write SynchronizationReadWriteLock vs synchronized vs ReentrantLock60-Day LLD & Machine Coding Mastery Roadmap
The Four Pillars of OOPComposition, Asociation & AggregationDatabase locking / atomic updates
Don't Repeat Yourself (DRY) PrincipleKeep it Simple, Stupid (KISS) PrincipleYou Aren't Gonna Need It (YAGNI) Principle
Design a Library Management System (LMS)Design a News FeedDesign a Parking LotDesign Thread-Safe Dropbox File Storage SystemDesign Tic Tac ToeDesing a Vending Machine
D : Dependency InversionI : The Interface Segregation PrincipleL : The Liskov Substitution PrincipleO : The Open/Closed PrincipleS : The Single Responsibility Principle
UML Activity Diagrams: Modeling Process and WorkflowUML Class Diagrams: Static Structure ModelingUML Sequence Diagrams: Modeling Dynamic InteractionsUse Case Diagrams: Functional Requirement Modeling
Low Level Design/problems

Design Tic Tac Toe

31 min read
On this page0. Problem overview
0. Problem overviewVariant A: Basic machine-coding Tic-Tac-ToeVariant B: Configurable-board Tic-Tac-ToeVariant C: AI-enabled Tic-Tac-ToeVariant D: Online multiplayer Tic-Tac-Toe2.1 Questions to ask2.2 Functional requirements2.3 Non-functional requirements2.4 Explicit out-of-scope decisions3.1 Core entities4.1 Symbol4.2 Player4.3 Cell4.4 Board4.5 Move4.6 Position4.7 GameStatus4.8 GameResult4.9 GameRelationships7.1 Sequence diagram7.2 Why check winner before draw?7.3 Why switch only after a successful non-terminal move?Enum vs State pattern9.1 Approach 1: Full board scan9.2 Approach 2: Check only the affected lines9.3 Approach 3: Per-player row and column countersWhy separate counters workImportant limitation9.4 Approach 4: Signed counters9.5 Approach 5: Generalized K-in-a-row9.6 Algorithm comparisonInterview recommendation10.1 Two-dimensional array10.2 One-dimensional array10.3 Enum vs PlayingPiece classes11.1 Core APIs11.2 Online REST APIs12.1 Race condition example12.2 Protect the complete move transition12.3 Per-game lock12.4 Optimistic concurrency12.5 Local lock vs distributed coordination12.6 Idempotency and duplicate requests13.1 Strategy patternPlayerStrategyWinStrategy13.2 Observer pattern13.3 Factory pattern13.4 State pattern13.5 Command pattern13.6 Memento pattern13.7 Pattern summary15.1 Configurable board size15.2 AI opponentRandom strategyMinimax strategy15.3 Undo and redo15.4 Replay15.5 Scoreboard and tournament manager15.6 Multiple players15.7 Online multiplayerComponent responsibilitiesPossible persistence model19.1 Unit tests19.2 Concurrency tests19.3 Property-based tests22.1 Recommended order22.2 Minimum viable class set22.3 Suggested 45–60 minute interview allocationObject modellingAlgorithmsState and correctnessDesign patternsConcurrencyExtensionsThe most important lessons

# 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:

  1. Object modelling and responsibility assignment.
  2. Encapsulation and invariants.
  3. Game lifecycle and state transitions.
  4. Move validation and turn management.
  5. Algorithm design and optimization.
  6. Strategy pattern and extensibility.
  7. Concurrency and atomic state changes.
  8. Testing and edge-case handling.
  9. 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

QuestionBaseline 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

  1. Create a game.
  2. Initialize an empty board.
  3. Create two players.
  4. Assign a unique symbol to each player.
  5. Start the game.
  6. Track the current player.
  7. Accept a move from the current player.
  8. Validate player identity and move position.
  9. Reject moves on occupied cells.
  10. Update the board after a valid move.
  11. Detect a winner.
  12. Detect a draw.
  13. Switch turns when the game continues.
  14. Prevent moves after the game ends.
  15. 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

EntityResponsibility
PlayerRepresents a participant
BoardOwns the grid and cell state
CellRepresents one board position, if modelled explicitly
GameCoordinates turns, moves, rules, and lifecycle
MoveRecords a committed move
PositionRepresents row and column
GameResultRepresents the final outcome
WinStrategyDetermines whether a move wins
PlayerStrategyChooses 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
    EMPTY

Why 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
    type

Where:

  • 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
    symbol

Responsibilities:

  • 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
    occupiedCount

Responsibilities:

  • 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
    timestamp

Responsibilities:

  • 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
    column

A 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
    ABORTED

Terminal 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 X

This generalizes better if symbols or player identities change.

# 4.8 GameResult

Attributes:

GameResult:
    status
    winner
    winningLine

The winning line is optional, but useful for UI highlighting.

# 4.9 Game

Attributes:

Game:
    gameId
    board
    players
    currentPlayerIndex
    status
    winner
    moveHistory
    winStrategy

Responsibilities:

  • 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.

ComponentResponsibility
UICollect player input and display output
ControllerTranslate input into game commands
GameEnforce game rules
BoardOwn grid state
WinStrategyDetect winning lines
Move historyStore 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) -> MoveResult

The move must be processed in this order:

  1. Check whether the game is in progress.
  2. Check whether the player belongs to the game.
  3. Check whether it is that player's turn.
  4. Validate the coordinates.
  5. Check whether the cell is empty.
  6. Place the symbol.
  7. Record the move.
  8. Check for a win.
  9. If no win, check for a draw.
  10. If neither, switch turns.
  11. 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 player

# 7.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 true

The 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:

  1. Row r.
  2. Column c.
  3. Main diagonal, if r == c.
  4. 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 = player

Each 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 O

X's count is 2, not 3.

O's count is 1.

If a row contains:

X X X

X'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 O

Total = +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 player

The 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

ScenarioRecommended approachComplexity per move
Simple 3×3Full scan or affected-line scanO(1) for fixed 3
N×N, complete line requiredAffected-line scanO(N)
N×N, complete line requiredPer-player countersO(1)
Larger board, K consecutive marksDirectional scanO(K)
Very small board, easiest implementationFull scanO(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 + column

Reverse:

row = index / N
column = index % N

Useful 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
    EMPTY

Board:

Symbol[][] cells

Advantages:

  • Simple.
  • Type-safe.
  • Minimal classes.
  • Appropriate for fixed symbols.

Design B: Polymorphic PlayingPiece

PlayingPiece
    PlayingPieceX
    PlayingPieceO

Board:

PlayingPiece[][] cells

Advantages:

  • 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) -> MoveResult

MoveResult should include:

success
errorCode
gameStatus
nextPlayer
winner
winningLine
boardSnapshot

Error codes might include:

INVALID_PLAYER
NOT_YOUR_TURN
OUT_OF_BOUNDS
CELL_OCCUPIED
GAME_NOT_STARTED
GAME_OVER

# 11.2 Online REST APIs

POST /games
GET /games/{gameId}
POST /games/{gameId}/moves
GET /games/{gameId}/moves
POST /games/{gameId}/abort
POST /games/{gameId}/rematch

Example 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:

  1. Read currentPlayer = X.
  2. Validate the move.
  3. Place X.
  4. Advance the turn.

Both moves may be marked X.

This corrupts the game.

# 12.2 Protect the complete move transition

The critical section includes:

  1. Game status check.
  2. Player identity check.
  3. Turn check.
  4. Position validation.
  5. Occupancy validation.
  6. Board update.
  7. Counter update.
  8. Move history update.
  9. Win/draw check.
  10. 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
    version

A 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) -> Position

Implementations:

  • HumanStrategy.
  • RandomStrategy.
  • MinimaxStrategy.

# WinStrategy

Determines whether a move has created a winning condition.

interface WinStrategy:
    checkWinner(board, lastMove) -> result

Implementations:

  • 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
    result

The 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

PatternRecommendation
StrategyUseful for AI and configurable win rules
ObserverOptional for game events
FactoryOptional for multiple player types/configurations
StateUsually unnecessary
CommandOptional for undo/replay
MementoOptional for snapshots
RepositoryOnly if persistence is required
SingletonAvoid
FacadeUsually unnecessary

# 14. SOLID principles

PrincipleApplication
Single ResponsibilityBoard owns cells; Game owns turn and lifecycle
Open/ClosedAdd new win strategies without rewriting Game
Liskov SubstitutionEvery WinStrategy must honour the same contract
Interface SegregationKeep PlayerStrategy and WinStrategy separate
Dependency InversionGame 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

  1. Find empty cells.
  2. Select one randomly.
  3. 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           0

Algorithm:

  1. Generate legal moves.
  2. Simulate a candidate move.
  3. Evaluate terminal states.
  4. Recursively evaluate opponent responses.
  5. Maximize AI score.
  6. Minimize opponent score.
  7. 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:

  1. Remove the last move from history.
  2. Clear the corresponding board cell.
  3. Decrease occupied count.
  4. Restore the previous player.
  5. Restore game status.
  6. Restore winner information.
  7. 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

  1. Create a new game with the same configuration.
  2. Apply recorded moves in order.
  3. Validate each move.
  4. 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

ComponentResponsibility
AuthenticationIdentify caller
Game ServiceCreate, join, fetch, and manage games
Game EngineValidate and apply moves
Game RepositoryLoad and persist state
DatabaseStore game, player, and move records
Event PublisherPublish committed game events
Notification ServiceNotify 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
    createdAt

Useful 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:

  1. A cell contains only X, O, or EMPTY.
  2. A cell can be occupied only once.
  3. X and O are assigned to different players.
  4. X starts.
  5. X count equals O count or is exactly one greater.
  6. Only the current player may move.
  7. A successful move increases occupied count by one.
  8. A rejected move changes no game state.
  9. A terminal game cannot accept moves.
  10. An IN_PROGRESS game has no winning line.
  11. An IN_PROGRESS game is not full.
  12. The move history must agree with the board.
  13. 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

ScenarioExpected behaviour
Negative rowReject
Negative columnReject
Row >= board sizeReject
Column >= board sizeReject
Occupied cellReject
Wrong playerReject
Player not in gameReject
Move after winReject
Move after drawReject
Invalid moveSame player retries
Final move winsDeclare win, not draw
Final move does not winDeclare draw
Aborted gameReject subsequent moves
Concurrent requestsAt most one legal transition commits
Duplicate online retryReturn original result if idempotency is supported
Read during moveReturn a consistent snapshot

# 19. Testing strategy

# 19.1 Unit tests

TestExpected result
Empty board creationAll cells EMPTY
Game creationCorrect players and board
First moveX placed
Second moveO placed
Horizontal winWinner detected
Vertical winWinner detected
Main diagonal winWinner detected
Anti-diagonal winWinner detected
DrawDRAW
Occupied cellRejected
Out-of-boundsRejected
Wrong playerRejected
Move after winRejected
Move after drawRejected
Invalid moveNo state mutation

# 19.2 Concurrency tests

  1. Two requests try to play the same cell.
  2. Two requests try to move during the same turn.
  3. Two requests submit moves for different players simultaneously.
  4. Two requests race to fill the last cell.
  5. 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.

OperationComplexity
Initialize boardO(N²)
Validate coordinatesO(1)
Check cell availabilityO(1)
Place symbolO(1)
Check full board with occupied countO(1)
Check full board by scanningO(N²)
Full win scanO(N²)
Affected-line win scanO(N)
Counter-based win detectionO(1)
K-in-a-row directional scanO(K)
Board storageO(N²)
Per-player row/column countersO(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

MistakeWhy it is wrongBetter approach
Board as SingletonPrevents multiple independent gamesEach Game owns its Board
UI inside GameCouples domain to presentationSeparate controller
Direct external board mutationBypasses validationMutate through Game
No player identity validationAllows impersonation in online playValidate authenticated player
Check draw before winFinal move may winCheck win first
Switch after invalid moveWrong turn semanticsSwitch only after valid non-terminal move
Accept moves after game overBreaks lifecycle invariantCheck status first
Empty line treated as winIncorrect scan logicReject EMPTY candidate
Scan every line unnecessarilyWastes workCheck affected lines
Use whole-line counters for K-in-a-rowDoes not detect arbitrary contiguous runsDirectional scan
Lock only board writeTurn/status/history can raceLock complete transition
One global lockUnrelated games blockPer-game lock
Expose mutable arrayExternal corruptionSnapshot/read-only view
Overuse inheritanceUnnecessary complexityEnum for simple symbols
Too many patternsOverengineeringAdd only justified abstractions
AI logic in GameCouples decisions to rulesPlayerStrategy
Undo clears only cellOther derived state remains staleRestore or recompute all state

# 22. How to implement in a machine-coding interview

# 22.1 Recommended order

  1. Symbol enum.
  2. GameStatus enum.
  3. Player.
  4. Board.
  5. Game.
  6. MoveResult.
  7. Win detection.
  8. Driver / console interaction.
  9. Tests.

# 22.2 Minimum viable class set

ClassResponsibility
PlayerIdentity and symbol
BoardGrid and cell operations
GameTurns, validation, lifecycle
MoveResultResult of a move
SymbolX, O, EMPTY
GameStatusIN_PROGRESS, WON, DRAW

Add strategy and history only when requirements call for them.

# 22.3 Suggested 45–60 minute interview allocation

TimeActivity
0–5 minClarify requirements
5–10 minDefine scope and assumptions
10–15 minIdentify entities
15–22 minDraw class diagram
22–32 minImplement board and move flow
32–38 minImplement win/draw detection
38–43 minHandle invalid moves and lifecycle
43–48 minExplain concurrency
48–55 minDiscuss AI, undo, N×N, online game
55–60 minTest and summarize trade-offs

# 23. Interview follow-up questions

# Object modelling

  1. Why is Board separate from Game?
  2. Why should Board not manage the current player?
  3. Do we need a Cell class?
  4. Should we use enum or PlayingPiece subclasses?
  5. Why should Board not be a Singleton?
  6. What should Move contain?
  7. Should Game own Player objects or reference them?

# Algorithms

  1. How do you detect a winner?
  2. Why can you check only the last move's row, column, and diagonals?
  3. How do you optimize winner detection to O(1)?
  4. Why do counter-based algorithms work?
  5. Why do they not solve arbitrary K-in-a-row?
  6. How do you detect K consecutive marks?
  7. How do you detect a draw efficiently?

# State and correctness

  1. What happens if a player selects an occupied cell?
  2. Why check win before draw?
  3. Why switch turn only after a successful move?
  4. How do you prevent moves after a game ends?
  5. What invariants should always hold?

# Design patterns

  1. Where would you use Strategy?
  2. Why separate PlayerStrategy from WinStrategy?
  3. Is State pattern necessary?
  4. Where can Observer be useful?
  5. How would Command help undo?
  6. Would you use Factory?

# Concurrency

  1. What happens if both players submit moves simultaneously?
  2. Why is locking only the Board insufficient?
  3. Why use a per-game lock?
  4. How would multiple application instances coordinate?
  5. How would optimistic locking work?
  6. How would you handle duplicate requests?

# Extensions

  1. How do you add AI?
  2. How does minimax work?
  3. How do you support configurable board size?
  4. How do you support K-in-a-row?
  5. How do you implement undo?
  6. How do you implement replay?
  7. How do you support multiple games?
  8. 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
MoveResult

Use:

  • 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
GameRepository

Do not implement these all up front.

# The most important lessons

  1. Model responsibilities, not just nouns.
  2. Keep Board and Game separate.
  3. Keep UI separate from domain logic.
  4. Make invalid moves side-effect free.
  5. Understand the difference between whole-line and K-in-a-row rules.
  6. Understand both affected-line scanning and counter-based optimization.
  7. Protect the complete game transition under concurrency.
  8. Use Strategy for genuinely variable behaviour.
  9. Treat undo as reversal of all state, not just the board cell.
  10. Separate local machine coding from online multiplayer architecture.
  11. Prefer simple, correct design over unnecessary abstractions.
  12. Be able to explain why each class exists and what would change if a requirement were added.
←PreviousDesign Thread-Safe Dropbox File Storage SystemNext→Desing a Vending Machine

On this page

0. Problem overviewVariant A: Basic machine-coding Tic-Tac-ToeVariant B: Configurable-board Tic-Tac-ToeVariant C: AI-enabled Tic-Tac-ToeVariant D: Online multiplayer Tic-Tac-Toe2.1 Questions to ask2.2 Functional requirements2.3 Non-functional requirements2.4 Explicit out-of-scope decisions3.1 Core entities4.1 Symbol4.2 Player4.3 Cell4.4 Board4.5 Move4.6 Position4.7 GameStatus4.8 GameResult4.9 GameRelationships7.1 Sequence diagram7.2 Why check winner before draw?7.3 Why switch only after a successful non-terminal move?Enum vs State pattern9.1 Approach 1: Full board scan9.2 Approach 2: Check only the affected lines9.3 Approach 3: Per-player row and column countersWhy separate counters workImportant limitation9.4 Approach 4: Signed counters9.5 Approach 5: Generalized K-in-a-row9.6 Algorithm comparisonInterview recommendation10.1 Two-dimensional array10.2 One-dimensional array10.3 Enum vs PlayingPiece classes11.1 Core APIs11.2 Online REST APIs12.1 Race condition example12.2 Protect the complete move transition12.3 Per-game lock12.4 Optimistic concurrency12.5 Local lock vs distributed coordination12.6 Idempotency and duplicate requests13.1 Strategy patternPlayerStrategyWinStrategy13.2 Observer pattern13.3 Factory pattern13.4 State pattern13.5 Command pattern13.6 Memento pattern13.7 Pattern summary15.1 Configurable board size15.2 AI opponentRandom strategyMinimax strategy15.3 Undo and redo15.4 Replay15.5 Scoreboard and tournament manager15.6 Multiple players15.7 Online multiplayerComponent responsibilitiesPossible persistence model19.1 Unit tests19.2 Concurrency tests19.3 Property-based tests22.1 Recommended order22.2 Minimum viable class set22.3 Suggested 45–60 minute interview allocationObject modellingAlgorithmsState and correctnessDesign patternsConcurrencyExtensionsThe most important lessons