Design tic-tac-toe
easy 70 minModel a game everybody knows: marks on a grid, turns, a full line wins.
Video lesson · Chapter 1 of 6
Make a prediction
Tic-tac-toe LLD in 90 seconds
1:27Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
Tic-tac-toe in a low-level design round is a referee: an object that stores a grid, allows legal moves in turn, and says when the game is won or drawn. Screens, players and scores are around it.
It is a small state machine with a history. Its state changes only through one method, which first asks whether it may. Orders, documents and accounts have the same shape.
The technical idea in it is incremental checking: do not ask whether there is a winner somewhere, ask what the last move can have changed.
Why it exists
It needs no explanation, so an interviewer sees your habits at once: where input goes, where rules go, what is checked before what.
It is small enough to be proved by trying everything. Few programs give you the chance to check all runs, and using it says much about a person.
It grows in every direction: size, players, rules, opponents, networks. Each wish presses on another seam of the design.
A short history
1858
The name noughts and crosses is found in print, in an issue of Notes and Queries. The game itself is much older.
1952
Sandy Douglas writes OXO, a program that plays the game on the EDSAC computer in Cambridge: one of the first games with a screen.
1961
Donald Michie builds MENACE with Roger Chambers: matchboxes with beads that learn the game. One box for each position, up to turning and mirroring.
1994
The book Design Patterns describes Command, with undo as its example of use.
Words to know
- Mark
- X or O. Not the player: the player is whoever uses it.
- Line
- A row, a column or one of two diagonals: 2n + 2 of them.
- Incremental check
- Looking only at what the last change can have affected.
- Legal move
- The game goes on, it is your turn, the square is inside and empty.
- Invariant
- A sentence that is true after every call, such as: a count is the number of marks on a line.
- Opposite or inverse
- The operation that brings back the state before another one.
- Replay
- Building the state again by playing the stored moves.
- Minimax
- The value of a position is the best of what the opponent leaves, seen from each side in turn.
- Position
- What lies where and who moves. Many games lead to one position.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
Solve it like an interview
New to it? Start with Approach. Revising? Go straight to the mock.
- 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
- 2ScopeAsk what changes the design, then commit to a short list.
- 3API and dataThe contract first, then the data that serves it.
- 4DesignStart with the smallest system that works. Change it only when something breaks.
- 5Deep divesCompare the options before you open them, then say which you would pick.
- 6Explain your choicesAnswer first. Then compare your reasoning.
- 7By levelThe same question is judged differently for mid, senior and staff.
- 8MockAnswer against the clock, then score yourself.
How it works
Step through the idea, or press Play.
A move is asked for. Going on, right turn, inside, empty
Understand it
Start here
Pebbles and shells on the sand
Two children, nine squares in the sand, and the sea behind them. Asha has pebbles, Noor has shells. Watch four things: who is allowed to play, what a move changes, how somebody notices a win, and what is left when the water comes.
The board stores, the sticks see, the children take turns, and the tide shows what should have been kept elsewhere.
What an interviewer looks for here
Where is the turn checked?
In the game, for every caller. Not in the screen and not in the player.
What does a move change?
One square and at most four lines. A win check that knows this is O(1).
Is a refused move free?
After an error the state is exactly what it was.
Can it grow?
Size, players and undo arrive as follow-ups. None of them should open
BoardandGameat the same time.
Questions
Six questions, and what each answer changes
| Ask | If the answer is | Then |
|---|---|---|
| Only 3 by 3, or any size? | Any size n | No constants, and a win check that does not grow with n |
| Is a win always a full line? | Yes | Counting works. If k in a row is enough, it does not: see four in a row |
| Two people, or a computer? | Perhaps both | A player is whoever calls. An interface when the computer arrives |
| May a move be taken back? | Yes | Moves are stored, and each change has an opposite |
| One game, or many at the same time? | One, for now | No lock. A game has no global state, so many are easy later |
| Screen, saving, scores? | Out | Nothing in the game prints or reads |
States
The life of a game
Four states, three of them final
A call, from the outside to the squares
Design, first try
The design most people write first
The design to avoid: the game is inside the screen, and the winner is inside the board
1/4One class from keyboard to verdict
Reading, printing, turns and winning in one class. There is no way to ask who has won without somebody typing.
owns (dies together)extends (is a)
class TicTacToe: def __init__(self): self.board = [[" "] * 3] * 3 # one row, seen three times self.player = "X" def run(self): while True: r, c = map(int, input().split()) self.board[r][c] = self.player # taken? outside? -1 is a place in Python if self.check_winner(): print(self.player, "won") return self.player = "O" if self.player == "X" else "X" def check_winner(self): for p in ["X", "O"]: for i in range(3): if all(self.board[i][j] == p for j in range(3)): return True if all(self.board[j][i] == p for j in range(3)): return True return False # diagonals? a draw?What each bug teaches
- 1
[[" "] * 3] * 3Three references to one row. A mark appears in all three. Build each row by itself.
- 2
Minus one
board[-1][0]is the last row in Python. Checking "too large" only is half a check. - 3
Input inside the rules
A test must fake a keyboard. A second screen must copy the rules.
- 4
Two marks in the check
Only the mark that has just been played can have completed a line. Looking for the other one is wasted and confusing.
- 5
No end
A full board without a line loops for ever, asking for a place that is not there.
Design, better
The design to reach
The design to reach: the board stores, the counts see wins, the game enforces
1/5The referee
Game knows whose turn it is and whether the game goes on. It is the only way to change anything, so a rule checked here is a rule.
owns (dies together)uses
game = Game()game.play(Mark.X, 1, 1) # Status.PLAYINGgame.play(Mark.X, 0, 0) # IllegalMove: not your turngame.undo() # the middle is empty, and it is X's turn againRoles
What each class owns
| Class | Knows | Does | Does not know |
|---|---|---|---|
Game | Turn, status, moves | Allows or refuses, in order | How a win is found, how squares are stored |
Board | What lies where, how many are empty | Stores and clears, refuses a taken square | Whose turn it is, what a line is |
LineCounts | Marks on each line | Says whether a move completed one | The squares |
Move | Row, column, mark | Nothing: a record | Whether it was legal |
| A player | Its own plans | Calls play | The inside of the game |
Winning
What can one move change?
A pebble in row 1, column 2 can complete row 1 or column 2. If it lies on a diagonal, also that one. It can complete nothing else. So four looks are enough, if each line remembers how full it is.
Counts for X in the game on the sand
| Move | row 0 | row 1 | row 2 | col 0 | col 1 | col 2 | down | up |
|---|---|---|---|---|---|---|---|---|
| X (1,1) | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 1 |
| X (0,2) | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 2 |
| X (1,0) | 1 | 2 | 0 | 1 | 1 | 1 | 1 | 2 |
| X (1,2) | 1 | 3 | 0 | 1 | 1 | 2 | 1 | 2 |
Which lines does a square belong to?
How do you find out that somebody has won?
BreaksRead the whole board after each move
- How
- For each of 2n + 2 lines, look at n squares.
- Limit
- n = 3: 24 looks. n = 1,000: two million for each move. It also checks the mark that has not moved.
- Choose when
- As the slow, believable version in a test.
WorksRead only the lines through the last move
- How
- Row, column, and diagonals if the square is on them: at most 4n looks.
- Limit
- Grows with n. Correct, stores nothing, and undo is free.
- Choose when
- A fine answer for small boards, and the one that survives k in a row.
StrongCount marks on each line
- How
- 2n + 2 counters for each mark. A move adds to at most four. Equal to n is a win.
- Limit
- Counters must be taken back on undo. Works only when a win is a full line.
- Choose when
- The base design here, because the answer to question two was yes.
Taking back
Every change has an opposite
| play does | undo does |
|---|---|
| Append the move | Pop the move |
| Put the mark, one empty square fewer | Clear the square, one more |
| Add one to its lines | Take one from its lines |
| Pass the turn, unless the game ended | Give the turn to whoever made the move |
| Set the status | Set PLAYING: before a legal move the game was always going on |
move.mark is always right.Summary
The whole topic in one minute.
The game enforces turns and the end, the board stores squares and refuses taken ones, counters see a full line in at most four steps. All questions come before all changes, the win before the draw.
A move is an object, so it can be taken back by opposites, replayed, stored and sent. Counting works because a win is a full line; for k in a row walk from the last move. A computer can know all 5,478 positions.
- The game enforces, the board stores, the counts see, the players only wish.
- One move touches at most four lines. Count them.
- Win first, then full. The last square can do both.
- A refused move changes nothing.
- Ask whether a win is a full line. If not, counting is wrong.