Design Connect Four
🔴 What is Connect Four? Two players take turns dropping colored discs into the columns of an upright grid, usually 6 rows by 7 columns. A disc falls to the lowest empty cell of its column. The first player to line up four of their discs in a row, horizontally, vertically or diagonally, wins. If the grid fills up first, the game is a draw.
Connect Four looks like tic-tac-toe with a taller board, and that is exactly the trap. Two rules change the design: players pick a column, not a cell, so the game has to work out where the disc lands (gravity), and a win is four in a row anywhere on a board that is bigger than four, so the clever counting trick from /low-level-design/tic-tac-toe no longer works. The interviewer wants to see you handle both cleanly and check for a winner without scanning the whole board.
Requirements
"Design the game Connect Four for two players."
Short prompts like this one are an invitation to ask. These are the questions whose answers change the code.
Clarifying Questions
You: What size is the board? Always 6 by 7?
Interviewer: 6 by 7 is the standard, but take the number of rows and columns when the game is created.
You: What exactly counts as a win?
Interviewer: Four or more discs of the same player in an unbroken line: horizontal, vertical, or either diagonal.
You: How do players move, and do we enforce turns?
Interviewer: A player picks a column and the disc falls to the lowest free cell. Player 1 always starts, then they alternate. Reject a move by the wrong player.
You: What about a full column, or a column that does not exist?
Interviewer: Reject the move and change nothing; it is still the same player's turn. Return an error value rather than throwing.
You: When does the game end?
Interviewer: When someone connects four, or when the board is full with no winner. That is a draw. After the end, reject every move.
You: Does anything need to read the board, like a screen?
Interviewer: Yes. The display asks what is in a given cell. Count rows from the bottom: row 0 is where the first disc in a column lands.
The last answer is worth asking for. Whether row 0 is the top or the bottom does not matter much in code, but if you and the interviewer assume different ones, every example you trace will look wrong to them. Pin it down once.
💡 Interview tip: When the interviewer says "standard board", still ask whether the size is fixed. Taking the size as a parameter costs nothing, and it makes your own tests much easier: a 4 by 4 board is far quicker to trace by hand than 6 by 7.
Final Requirements
- The board has a given number of rows and columns. Row 0 is the bottom; columns are numbered from 0 at the left.
- Player 1 moves first, then the players alternate.
- A move names a column and a player. The disc lands in the lowest empty cell of that column.
- A move is rejected, with no change, if the game is over, it is not that player's turn, the column does not exist, or the column is full.
- A player wins when the new disc is part of four or more of their discs in a line: horizontal, vertical or diagonal.
- If a disc fills the last empty cell without winning, the game is a draw.
- Each move returns its result: game continues, player 1 wins, player 2 wins, draw, or rejected.
- Anyone can read the contents of any cell.
Out of scope
- A user interface and animations of falling discs.
- Computer opponents, undo, other win lengths, and online play (all in Extensibility).
- Timers and ratings.
Entities and Relationships
Pick the nouns from the requirements that hold state or enforce a rule.
- ConnectFour: the game and the entry point. It enforces turns and the end of the game, decides whether a move won, and is the only class the caller talks to.
- Board: the grid. It knows where the next disc in each column will land, places discs, reports what is in a cell, and can count matching discs along a line.
- Status: an enum for the state of the game: in progress, player 1 won, player 2 won, draw.
And the nouns we will not turn into classes:
- Disc and Player are just the numbers 1 and 2. A disc has no behavior: it never moves once it lands. A cell holding
1says everything aDiscobject would. - Column is an index plus one number, its height. A list of heights inside
Boardis simpler than seven column objects. - Line and direction are a pair of steps like
(1, 1). We keep the four directions in a constant. - Move is the arguments of
drop. It becomes a small record only if we add undo.
Compared with tic-tac-toe there is one fewer class. There, the win check had its own state (the line counters), so it earned a WinTracker. Here the win check reads the board and keeps no state of its own, so it is a short method on the game.
| Owner | Owns | How many |
|---|---|---|
| ConnectFour | Board | exactly one |
| ConnectFour | Status | one current value |
| Board | grid cells | rows × cols integers |
| Board | column heights | one per column |
Class Design
Top down from the class the caller uses. The game should read like the rules; the board should know geometry and nothing about turns or winning lengths.
ConnectFour
The orchestrator. It checks each move, asks the board to place the disc, and turns the outcome into a result code.
class ConnectFour:
board: Board # requirements 1, 3, 8
turn: int # 1 or 2, requirement 2
status: Status # requirements 5, 6, 7
def __init__(self, rows: int = 6, cols: int = 7): ...
def drop(self, col: int, player: int) -> int: ... # 0, 1, 2, 3 or -1
def get_cell(self, row: int, col: int) -> int: ... # 0 empty, 1 or 2
def _connects(self, row: int, col: int) -> bool: ... # did the disc at (row, col) win?
drop takes a column, not a row, because that is what a player chooses. _connects takes the row too, because by then the board has told us where the disc landed, and the win check starts from that exact cell.
Board
The grid, with gravity built in.
class Board:
rows: int
cols: int
grid: List[List[int]] # grid[row][col], row 0 at the bottom; 0 empty, 1 or 2 a disc
heights: List[int] # discs in each column = the row the next disc lands in
discs: int # total discs, so is_full() is one comparison
def can_drop(self, col: int) -> bool: ...
def drop(self, col: int, player: int) -> int: ... # returns the landing row
def cell(self, row: int, col: int) -> int: ...
def is_full(self) -> bool: ...
def count_from(self, row: int, col: int, dr: int, dc: int) -> int: ...
heights is the key field, and we justify it in the Implementation section. count_from walks from a cell in one direction and counts matching discs; it is pure geometry, so it lives on the board, while the rule "four is a win" stays in the game.
Status and constants
class Status(Enum):
IN_PROGRESS = 0
PLAYER_1_WINS = 1
PLAYER_2_WINS = 2
DRAW = 3
INVALID = -1
WIN_LENGTH = 4
DIRECTIONS = [(0, 1), (1, 0), (1, 1), (1, -1)] # horizontal, vertical, two diagonals
The status values match the codes drop returns. WIN_LENGTH is a named constant rather than a 4 buried in a loop, which pays off in the first follow-up question.
Implementation
The work is in drop. We write it top to bottom, then look closely at its two interesting steps: finding the landing row, and deciding whether the disc won.
Dropping a disc
def drop(self, col: int, player: int) -> int:
if self.status != Status.IN_PROGRESS or player != self.turn:
return INVALID # game over, or not your turn (req. 2, 4)
if not self.board.can_drop(col):
return INVALID # no such column, or it is full (req. 4)
row = self.board.drop(col, player) # gravity (req. 3)
if self._connects(row, col): # requirement 5
self.status = Status.PLAYER_1_WINS if player == 1 else Status.PLAYER_2_WINS
elif self.board.is_full(): # requirement 6
self.status = Status.DRAW
else:
self.turn = 3 - self.turn # 1 -> 2, 2 -> 1
return self.status.value
The shape is the same as any turn-based game: validate everything first, then change state, then decide the outcome. Validation before change is what makes "reject and change nothing" true. Win before draw matters because the disc that fills the board can also connect four, and that is a win.
Finding where the disc lands
The player chose a column. Which row does the disc end up in?
Bad Solution: scan the column
Approach
Look up the column from the bottom until you find an empty cell.
def landing_row(self, col: int) -> int:
for row in range(self.rows):
if self.grid[row][col] == 0:
return row
return -1 # the column is full
Challenges
It works, and on a 6-row board it is cheap. But it does a little search on every move to recover a fact we could simply remember, and the "is the column full?" check becomes a side effect of that search. It also hides a bug risk: if the grid ever had a gap (it should not, but a future "pop out the bottom disc" variant would create one temporarily), the scan would happily drop a disc into the middle of a column.
Good Solution: keep a height per column
Approach
Each column remembers how many discs it holds. That number is also the row where the next disc lands, because rows count from the bottom.
def can_drop(self, col: int) -> bool:
return 0 <= col < self.cols and self.heights[col] < self.rows
def drop(self, col: int, player: int) -> int:
row = self.heights[col]
self.grid[row][col] = player
self.heights[col] += 1
self.discs += 1
return row
Challenges
Both methods are O(1), and "the column is full" becomes a plain comparison, heights[col] == rows. The cost is one more field to keep in sync with the grid, and drop is the only method that writes either, so they cannot drift apart. This is also where choosing row 0 at the bottom pays off: the height and the landing row are the same number. With row 0 at the top, the landing row would be rows - 1 - heights[col], which works but is one more thing to get wrong under pressure.
A Great option is not needed here. O(1) is as fast as it gets, and anything fancier would only add state.
Checking for a winner
The new disc is at (row, col). Did it complete four in a row?
Bad Solution: scan the whole board
Approach
After every move, try every cell as the start of a line in each of the four directions, and check the next three cells.
def has_four(self) -> bool:
b = self.board
for r in range(b.rows):
for c in range(b.cols):
p = b.grid[r][c]
if p == 0:
continue
for dr, dc in DIRECTIONS:
end_r, end_c = r + 3 * dr, c + 3 * dc
if 0 <= end_r < b.rows and 0 <= end_c < b.cols and \
all(b.grid[r + i * dr][c + i * dc] == p for i in range(4)):
return True
return False
Challenges
It is correct, and it is a reasonable thing to say first. But it does roughly rows × cols × 4 × 4 reads on every move, almost all of them about discs that have not changed. It also gets the bounds checks wrong easily: forgetting that the falling diagonal (1, -1) moves left is the classic off-by-one. And it ignores the key fact: a new win must include the new disc.
Good Solution: walk out from the last disc
Approach
Only lines through the new disc can be new wins. For each of the four directions, count matching discs going forward and going backward from the new disc, then add one for the disc itself. If any direction reaches four, the player won.
def count_from(self, row: int, col: int, dr: int, dc: int) -> int:
player = self.grid[row][col]
count = 0
r, c = row + dr, col + dc
while 0 <= r < self.rows and 0 <= c < self.cols and self.grid[r][c] == player:
count += 1
r += dr
c += dc
return count
def _connects(self, row: int, col: int) -> bool:
for dr, dc in DIRECTIONS:
length = 1 + self.board.count_from(row, col, dr, dc) + self.board.count_from(row, col, -dr, -dc)
if length >= WIN_LENGTH:
return True
return False
Challenges
Each move now reads at most a few cells in each direction: a handful of reads no matter how big the board is. Only four directions are listed, because walking backward along (1, 1) covers (-1, -1); the minus signs give us the other half of each line for free.
Counting both ways is the part people miss. If you only walk forward from the new disc, you catch it when it sits at the end of a line but not when it fills a gap in the middle. Picture 1 1 _ 1 on the bottom row: player 1 drops into the gap, and the new disc has one match on its left and one on its right. Counting one way finds two; counting both ways finds four.
⚠️ Common mistake: Checking only "the three discs below and to the right of the new one". A disc can complete a line from the middle. Always count in both directions and add one for the disc itself.
Why not reuse the running counters from tic-tac-toe? There, a win means a whole row, so one number per row can tell us when a row is all one player. Here, a win is any four in a row, and a row of seven can hold four of your discs in a row and also discs of the other player. A sum cannot tell 1 1 1 1 2 2 2 apart from 1 2 1 2 1 1 2. The walk-out check is the right tool when the line you need is shorter than the board.
A Great option exists but is not worth it here: game engines store each player's discs as bits in a 64-bit number and test for four in a row with a few shifts and ANDs. It is very fast for a solver that checks millions of positions, but in an interview it trades readability for speed you do not need. Mention it only if asked how a strong computer player would search.
Edge cases
Each one maps to a line that is already in the code:
- Full column:
can_dropcompares the height withrowsand rejects. The turn does not change. - Column out of range, including negative:
can_dropchecks0 <= col < colsbefore it readsheights[col]. In Python,heights[-1]would silently read the last column, so the explicit range check is not optional. - Wrong player or game over: rejected before the board is touched.
- The new disc is in the middle of the line: counting both ways covers it.
- More than four in a row:
length >= WIN_LENGTH, not==, so filling the gap in1 1 _ 1 1is a win. - Win on the last free cell:
_connectsruns beforeis_full, so it is reported as a win. - Tiny boards: on a 3 by 3 board nobody can ever connect four, and the game simply ends in a draw when the board fills up. On a 1 by 1 board the first drop is a draw.
Verification
Let's trace the standard 6 by 7 board with the same sequence as the first practice test. heights lists columns 0 to 6.
| # | Call | What happens | Returns |
|---|---|---|---|
| 1 | drop(3, 1) |
Lands in row 0. heights = [0,0,0,1,0,0,0] | 0 |
| 2 | drop(3, 2) |
Lands on top, in row 1. heights[3] = 2 | 0 |
| 3 | drop(4, 1) |
Row 0 of column 4 | 0 |
| 4 | drop(4, 2) |
Row 1 of column 4 | 0 |
| 5 | get_cell(1, 3) |
Player 2's disc from step 2 | 2 |
| 6 | drop(5, 1) |
Row 0: player 1 has columns 3, 4, 5 on the bottom | 0 |
| 7 | drop(5, 2) |
Row 1: player 2 has columns 3, 4, 5 too | 0 |
| 8 | drop(6, 2) |
It is player 1's turn: rejected, nothing changes | -1 |
| 9 | drop(6, 1) |
Row 0 of column 6. Horizontal: 3 matches to the left + 0 to the right + 1 = 4 | 1 |
| 10 | drop(0, 2) |
The game is over: rejected | -1 |
| 11 | get_cell(0, 6) |
The winning disc | 1 |
Step 7 is a nice detail to point out: player 2 also has three in a row, but in row 1, and columns 2 and 6 are empty, so a disc there would fall to row 0 and not touch them. Gravity changes which threats are real. Step 8 shows that a rejected move leaves the turn with player 1. Step 9 shows the walk-out check in action: from (0, 6) it walks left and finds three discs, walks right and hits the edge, and adds one for the new disc.
Complete Code
Here is the full design in each language, the same code the practice tests run against.
from enum import Enum
from typing import List
INVALID = -1 # returned by drop() when the move is rejected
WIN_LENGTH = 4 # discs in a row needed to win
# One step along each kind of line: horizontal, vertical, and the two diagonals.
DIRECTIONS = [(0, 1), (1, 0), (1, 1), (1, -1)]
class Status(Enum):
IN_PROGRESS = 0
PLAYER_1_WINS = 1
PLAYER_2_WINS = 2
DRAW = 3
class Board:
"""The grid, with row 0 at the bottom. 0 is an empty cell, 1 and 2 are the players' discs."""
def __init__(self, rows: int, cols: int):
self.rows = rows
self.cols = cols
self.grid: List[List[int]] = [[0] * cols for _ in range(rows)]
self.heights = [0] * cols # discs in each column = the row the next disc lands in
self.discs = 0
def can_drop(self, col: int) -> bool:
return 0 <= col < self.cols and self.heights[col] < self.rows
def drop(self, col: int, player: int) -> int:
"""Puts a disc on top of the column and returns the row it landed in."""
row = self.heights[col]
self.grid[row][col] = player
self.heights[col] += 1
self.discs += 1
return row
def cell(self, row: int, col: int) -> int:
return self.grid[row][col]
def is_full(self) -> bool:
return self.discs == self.rows * self.cols
def count_from(self, row: int, col: int, dr: int, dc: int) -> int:
"""How many discs of the same player follow (row, col) in direction (dr, dc)."""
player = self.grid[row][col]
count = 0
r, c = row + dr, col + dc
while 0 <= r < self.rows and 0 <= c < self.cols and self.grid[r][c] == player:
count += 1
r += dr
c += dc
return count
class ConnectFour:
def __init__(self, rows: int = 6, cols: int = 7):
self.board = Board(rows, cols)
self.turn = 1 # player 1 always starts
self.status = Status.IN_PROGRESS
def drop(self, col: int, player: int) -> int:
if self.status != Status.IN_PROGRESS or player != self.turn:
return INVALID # the game is over, or it is not this player's turn
if not self.board.can_drop(col):
return INVALID # no such column, or the column is full
row = self.board.drop(col, player)
if self._connects(row, col):
self.status = Status.PLAYER_1_WINS if player == 1 else Status.PLAYER_2_WINS
elif self.board.is_full():
self.status = Status.DRAW
else:
self.turn = 3 - self.turn # 1 -> 2, 2 -> 1
return self.status.value
def get_cell(self, row: int, col: int) -> int:
return self.board.cell(row, col)
def _connects(self, row: int, col: int) -> bool:
# Only lines through the new disc can be new wins. Count both ways along each line.
for dr, dc in DIRECTIONS:
length = 1 + self.board.count_from(row, col, dr, dc) + self.board.count_from(row, col, -dr, -dc)
if length >= WIN_LENGTH:
return True
return False
Try it yourself: the Practice button above runs your code against the same interface.
Extensibility
These are the follow-ups interviewers like for Connect Four. For each one, say which class absorbs the change and which classes stay the same.
1) How would you support "connect K" and other board sizes?
Board size is already a constructor argument. The win length is a constant, so turning it into a field is a one-line change, and _connects already compares against it.
class ConnectFour:
def __init__(self, rows: int = 6, cols: int = 7, win_length: int = 4):
self.board = Board(rows, cols)
self.win_length = win_length
...
def _connects(self, row: int, col: int) -> bool:
for dr, dc in DIRECTIONS:
length = 1 + self.board.count_from(row, col, dr, dc) + self.board.count_from(row, col, -dr, -dc)
if length >= self.win_length:
return True
return False
Board does not change at all, which is the payoff for keeping "four" out of it. The check still costs O(K) per move. Ask one question: if K is larger than both the rows and the columns, nobody can ever win, so should the constructor reject that setup? Usually yes, with a clear error.
2) How would you add undo and replay?
Keep a history of the columns that were played. Undo pops the last column, lowers its height and clears the cell. Because discs only ever sit on top of a column, the last move is always the top disc of its column, so we do not even need to store the row.
def drop(self, col: int, player: int) -> int:
...
row = self.board.drop(col, player)
self.history.append(col)
...
def undo(self) -> bool:
if not self.history:
return False
col = self.history.pop()
player = self.board.remove_top(col) # lowers heights[col], clears the cell, discs -= 1
self.turn = player # it is that player's turn again
self.status = Status.IN_PROGRESS # undoing a winning or drawing move reopens the game
return True
Replay is the same history read forward: create a fresh game and call drop for each column with the alternating player. The history is a complete, tiny record of the game, so it is also the natural thing to save or send to a spectator. If undo and redo grow beyond one kind of action, each move can become a command object with apply and revert, which is the Command pattern; for one kind of move, a list of column numbers is enough.
3) How would you add a computer opponent?
A computer player needs behavior (choosing a column), so a Player interface earns its place now, as a Strategy. The game class does not change; a small loop outside it asks the current player for a column.
class Player:
def choose_column(self, game: ConnectFour) -> int:
raise NotImplementedError
class WinOrBlockPlayer(Player):
"""Take a winning column if there is one, else block the opponent's, else the center-most open column."""
def choose_column(self, game: ConnectFour) -> int:
open_cols = [c for c in range(game.board.cols) if game.board.can_drop(c)]
me, them = game.turn, 3 - game.turn
for who in (me, them):
for col in open_cols:
if game.would_connect(col, who): # drop, check, undo
return col
return min(open_cols, key=lambda c: abs(c - game.board.cols // 2))
would_connect is where the undo from the previous question pays off: drop a disc, run _connects, then remove the disc again. A stronger player searches several moves ahead (minimax) and uses the same drop-and-undo pair thousands of times, which is the only point where the bitboard trick from the Implementation section starts to matter. See /low-level-design/strategy-pattern.
4) How would you run online games with turn timers?
A server keeps a map from game id to game, with one lock per game so two requests for the same game cannot interleave. Without it, a double-click could pass the "is it your turn?" check twice before turn changes, and the same player would drop two discs.
class GameService:
def __init__(self, turn_limit: int):
self.games: Dict[str, ConnectFour] = {}
self.locks: Dict[str, threading.Lock] = {}
self.last_move_at: Dict[str, int] = {}
self.turn_limit = turn_limit
def drop(self, game_id: str, col: int, player: int, timestamp: int) -> int:
with self.locks[game_id]:
game = self.games[game_id]
if timestamp - self.last_move_at[game_id] > self.turn_limit:
return game.forfeit(game.turn) # the slow player loses
result = game.drop(col, player)
if result != INVALID:
self.last_move_at[game_id] = timestamp
return result
The timer lives in the service, not in ConnectFour, because "how long a player may think" is a rule of the online product, not of the game. The game only needs one new method, forfeit, that ends it with a win for the other player. Passing time in as an argument keeps everything testable. See /low-level-design/race-conditions-and-locks for the locking details.
💡 Interview tip: Put new rules in the narrowest place that owns them. Win length belongs to the game, timers belong to the online service, and the board stays pure geometry. Saying where each rule lives, and why, is what separates a design from a pile of code.
What is Expected at Each Level?
Junior
A junior candidate should model a grid and a game, drop discs into the right row, alternate turns, and detect four in a row, even by scanning the whole board after each move. With hints they should handle full columns, columns off the board and the draw, and trace a short game by hand.
Mid-level
A mid-level candidate asks about board size, win rules, row numbering and what illegal moves return. They keep a height per column so drops are O(1), check only the lines through the new disc, and count in both directions so a disc that fills a gap is caught. They know why a negative column index must be checked explicitly and why a win on the last cell is not a draw.
Senior
A senior candidate does all of that quickly and explains the design choices: why Disc and Column are not classes, why "four" lives in the game and not the board, and why tic-tac-toe's running counters do not carry over. On follow-ups they show the change lands in one place: a win_length field for connect K, a column history for undo and replay, a Player strategy that reuses undo for lookahead, and a service with a lock per game and turn timers kept outside the game itself.