AlgoViz

Design four in a row

medium 75 min

Model a game in which balls fall into tubes and four in a line win.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:35

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

  1. 1952

    Christopher Strachey uses one bit for each square of a board in a draughts program on the Ferranti Mark 1: an early bitboard.

  2. 1958

    Allen Newell, Herbert Simon and others publish early forms of the cut-off idea that is now called alpha-beta.

  3. 1970

    Albert Zobrist describes keys for positions that change by one exclusive-or for each move.

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

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

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 3

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 tubes in the toy shop
0123456

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

AskIf the answer isThen
How many tubes, how high, how many in a line?7, 6 and 4, but configurableThree 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?RedThe turn is the number of drops, odd or even
Must the winning line be shown?YesThe check returns the spots, not a yes or no
May a drop be taken back?YesA list of drops
Computer, or two devices?LaterNo input, no global state: a match or a program is another caller
The fourth question is small and changes a return type. Ask it before you write the check.

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 is pop
  • 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

The spot comes back from the rack and becomes the start of the search. If the caller passed a row, there would be two opinions.

Design, first try

The design most people draw first

The design to avoid: a grid in which balls can float

BallGame- grid: Cell[6][7]- heights: int[7]- current: Player- winner: Player+ place(row, col): bool+ findFreeRow(col): int+ checkHorizontal(): bool+ checkVertical(): bool+ checkDiagonal1(): bool+ checkDiagonal2(): boolCell- row, col: int- ball: Ball+ setBall(ball)

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)

Python
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 0
Before. Indexes that leave the grid, a direction that is missing, the number four in nine places, and a look at everything for a move that changed one place.

Four ideas that repair it

  1. 1

    Reading outside is empty

    at answers nothing for a place outside. Then no loop needs bounds.

  2. 2

    Directions are data

    Four pairs of numbers, one loop. A missing direction is visible in a list of four.

  3. 3

    Both ways

    The new ball may be in the middle of a line. Walk one way, then the other, and add.

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

Rack- tubes: List<List<Ball>>- height: int+ drop(tube, ball): Spot+ lift(tube): Ball+ at(spot): Ball?+ openTubes(): List<int>«enum»BallRED, BLUEother: Ball

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)

Python
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 code
After. The caller names a colour and a tube. Height, line and turn are answers, not questions.

Roles

What each part owns

PartKnowsDoesDoes not know
RackBalls by tube, the greatest heightDrops, lifts, reads, refuses a full tubeTurns, lines
line_throughNothingFinds the line around a spotWho plays
GameDrops, status, winning lineAllows or refuses, asks for a lineHow balls are stored
SpotTube and heightNothing: a recordWhat lies there
BallThe other colourotherPlaces

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

(w−k+1) h+w (h−k+1)+2 (w−k+1)(h−k+1)(w-k+1)\,h + w\,(h-k+1) + 2\,(w-k+1)(h-k+1)
w = 7, h = 6, k = 4: 4 x 6 + 7 x 3 + 2 x 4 x 3 = 24 + 21 + 24 = 69.

Walking from the red ball in tube 4, height 3

DirectionOne wayOther wayLength
flattube 5: nothing, stoptube 3, height 3: blue, stop1
upheight 4: nothing, stopheight 2: blue, stop1
risingtube 5, height 4: nothing, stoptubes 3, 2, 1: red, red, red; tube 0: nothing, stop4
Two, two and five looks. The search ends at the first direction that is long enough. Falling was not needed.

The walk

Why four directions and not eight? Left and right are one line. Walking both ways and counting once keeps them together.

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

QuestionAnswer fromIf it were a field
Whose turn?len(drops) odd or evenMust 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 wonCan say red while the status says draw
How high is a tube?The length of its listMust follow every append and pop
How many balls are left?Places minus dropsTwo counters that nobody asks
The winner trick: the last drop was made by the other one, because the count has moved on. One line, and it cannot be old.

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