Design four in a row
medium 75 minModel a game in which balls fall into tubes and four in a line win.
Video lesson · Chapter 1 of 6
Make a prediction
Four in a row LLD in 90 seconds
1:29Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
Four in a row in a low-level design round is a referee for a game with gravity: a player names a tube, the ball falls, and the referee says where it landed and whether it made a line.
Its core is a search around a change. Instead of asking whether the whole state contains something, start at the one place that changed. Spell checkers, spreadsheets and compilers work in the same way.
It is also the first game that is too large to know. 42 places allow 4,531,985,219,092 positions, so a program must look ahead with a limit and estimate.
Why it exists
It shows whether somebody thinks about representation: the same rules need four careful methods on a grid, and none on lists that grow.
It shows whether repetition is seen. Four directions are four copies of a loop, or four pairs of numbers.
It leads naturally to questions with depth: bit tricks, searching with cut-offs, repeated messages and clocks. An interviewer can go wherever you are strong.
A short history
1952
Christopher Strachey uses one bit for each square of a board in a draughts program on the Ferranti Mark 1: an early bitboard.
1958
Allen Newell, Herbert Simon and others publish early forms of the cut-off idea that is now called alpha-beta.
1970
Albert Zobrist describes keys for positions that change by one exclusive-or for each move.
1988
James Allen announces on 1 October that whoever begins can win on 7 by 6. Victor Allis announces an independent solution on 16 October.
2008
Stefan Edelkamp and Peter Kissmann compute the number of positions: 4,531,985,219,092.
Words to know
- Tube
- A column that fills from below. Called tube here, so that nobody confuses it with a row.
- Spot
- A place: tube and height, with height 0 at the bottom.
- Direction
- A pair of steps. Four are enough, because both ways are walked.
- Derived
- Computed from something else instead of stored.
- Unrepresentable
- Cannot be written down with the chosen structure, so no check is needed.
- Bitboard
- One bit for each place, one number for each colour.
- Depth limit
- How many drops ahead a program looks before it estimates.
- Cut-off
- Not looking further because the other player would never allow it. Alpha-beta.
- Transposition table
- A memory from position to value. Many orders of drops lead to one position.
- Optimistic number
- The client says which version or move it means, and is refused if it is not the next one.
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 tube is named. Going on, right colour, room in the tube
Understand it
Start here
Coloured balls in glass tubes
In a toy shop stand seven glass tubes, each with room for six balls. Sam drops red ones, Lee drops blue ones. Four of one colour in a line win: flat, upright or slanted. Watch who decides where a ball lies, and how much one ball can change.
The tube decides the height, the last ball decides what to check. Two facts, and most of the design follows from them.
What an interviewer looks for here
Can a ball float?
In a grid it can, and every method must prevent it. In a list for each tube it cannot be written.
One walk or four loops?
Four directions are data. The loop is written once.
Where do you start to look?
At the ball that has just landed. 16 looks, not 276.
What is derived?
Turn and winner follow from the drops. Fields that follow are fields that disagree.
Questions
Six questions, and what each answer changes
| Ask | If the answer is | Then |
|---|---|---|
| How many tubes, how high, how many in a line? | 7, 6 and 4, but configurable | Three numbers in the constructor, none in a loop |
| Does a longer line count? | Yes: four or more | >=, and a walk that does not stop at four |
| Who begins? | Red | The turn is the number of drops, odd or even |
| Must the winning line be shown? | Yes | The check returns the spots, not a yes or no |
| May a drop be taken back? | Yes | A list of drops |
| Computer, or two devices? | Later | No input, no global state: a match or a program is another caller |
Shape
A list for each tube
Tubes: a list of lists that grow
- A floating ball cannot be represented
- The height of a tube is the length of its list
- A drop is
append, undo ispop - Reading a place needs a check of the length
Grid: 42 cells, empty or not
- A ball with nothing below it is possible
- The free row must be searched or stored a second time
- Undo must find the top ball
- Reading a place is one step
Who decides what
Design, first try
The design most people draw first
The design to avoid: a grid in which balls can float
1/5Forty-two cells
A grid can hold a ball with nothing under it. So each method must remember to look for the lowest free row, and one will forget.
owns (dies together)has (lives on)extends (is a)
def check_winner(grid): for r in range(6): for c in range(7): if grid[r][c] != 0: if grid[r][c] == grid[r][c+1] == grid[r][c+2] == grid[r][c+3]: # c+3 is outside return grid[r][c] if grid[r][c] == grid[r+1][c] == grid[r+2][c] == grid[r+3][c]: # r+3 too return grid[r][c] if grid[r][c] == grid[r+1][c+1] == grid[r+2][c+2] == grid[r+3][c+3]: return grid[r][c] # the other diagonal was forgotten return 0Four ideas that repair it
- 1
Reading outside is empty
atanswers nothing for a place outside. Then no loop needs bounds. - 2
Directions are data
Four pairs of numbers, one loop. A missing direction is visible in a list of four.
- 3
Both ways
The new ball may be in the middle of a line. Walk one way, then the other, and add.
- 4
Start at the new ball
Any line that was not there before contains it. Other lines were looked at when their last ball fell.
Design, better
The design to reach
The design to reach: tubes that fill from below, and one walk for all lines
1/5Tubes, not a grid
A list for each tube. A ball is appended, so it lies on the ones before it. A floating ball cannot be written down.
owns (dies together)depends onuseshas (lives on)
game = Game() # 7 tubes, height 6, four in a linegame.drop(Ball.RED, 3) # Spot(tube=3, height=0)game.drop(Ball.BLUE, 3) # Spot(tube=3, height=1)game.undo() # 3: the tube that was liftedGame(tubes=9, height=7, need=5) # another game, the same codeRoles
What each part owns
| Part | Knows | Does | Does not know |
|---|---|---|---|
Rack | Balls by tube, the greatest height | Drops, lifts, reads, refuses a full tube | Turns, lines |
line_through | Nothing | Finds the line around a spot | Who plays |
Game | Drops, status, winning line | Allows or refuses, asks for a line | How balls are stored |
Spot | Tube and height | Nothing: a record | What lies there |
Ball | The other colour | other | Places |
Lines
How many lines are there, and how many matter?
On 7 by 6 there are 24 flat lines of four, 21 upright, 12 rising and 12 falling: 69. Looking at all of them is 276 places. A new ball lies on at most 13 of them, and walking from it needs far fewer looks, because a walk ends at the first other ball.
Lines of k on a rack of w tubes and height h
Walking from the red ball in tube 4, height 3
| Direction | One way | Other way | Length |
|---|---|---|---|
| flat | tube 5: nothing, stop | tube 3, height 3: blue, stop | 1 |
| up | height 4: nothing, stop | height 2: blue, stop | 1 |
| rising | tube 5, height 4: nothing, stop | tubes 3, 2, 1: red, red, red; tube 0: nothing, stop | 4 |
The walk
How do you find a win?
BreaksCounters for each row, as in tic-tac-toe
- How
- Add one to the counts of tube, height and diagonals.
- Limit
- A row of seven may hold four red balls that do not touch. Counting forgets where.
- Choose when
- Only when a win is a full line.
WorksRead all 69 lines
- How
- Loops over the rack, after each drop.
- Limit
- 276 looks, and it also finds old lines. Correct.
- Choose when
- As the believable judge in a test, and when a move can shift many balls.
StrongWalk from the last ball
- How
- Four directions, both ways.
- Limit
- Needs to know where the ball landed.
- Choose when
- The base design: at most 20 looks on any size of rack, for four in a line.
Derived
What is not stored
| Question | Answer from | If it were a field |
|---|---|---|
| Whose turn? | len(drops) odd or even | Must be switched by drop and by undo, and not after a win |
| Who has won? | The one who is not next, if the status is won | Can say red while the status says draw |
| How high is a tube? | The length of its list | Must follow every append and pop |
| How many balls are left? | Places minus drops | Two counters that nobody asks |
Three states of a game
Summary
The whole topic in one minute.
A list for each tube makes floating balls impossible. The caller names a tube, the rack answers with a spot, and the walk starts there: four directions, both ways, outside is empty. Turn and winner follow from the number of drops.
The walk is right because a new line must contain the new ball. If a rule moves several balls, read everything. For a computer use bits, a depth limit, an estimate and cut-offs. For two devices give each drop a number.
- A list for each tube: a floating ball cannot be written.
- The caller chooses a tube, the rack answers with a spot.
- Walk from that spot: four directions, both ways, one loop.
- Turn and winner are derived from the number of drops.
- Line first, then full. Refuse before changing.
Sources
- OpenSpiel: connect_four.h
- PettingZoo: connect four
- Pascal Pons: solving the game, part 6, bitboard
- John Tromp: positions and the 1988 solutions
- OEIS A212693: positions after n drops
- Chessprogramming wiki: bitboards
- Chessprogramming wiki: alpha-beta
- Chessprogramming wiki: Zobrist hashing
- Kaggle: ConnectX
- RFC 9110: HTTP semantics, If-Match
- Java SE 21 API: Long.bitCount