Machine Coding Problem

Connect Four

macoAllgamesboard-modelingwin-detectionturn-order

Requirements & System Scope

Functional Scope (In-Scope)

  • Configurable Board: The row count and column count are inputs to Game, and the connect length N is an input to the win rule. The classic game is 6 rows, 7 columns and N = 4, but nothing in the code is tied to those numbers.
  • Gravity Drops: A move names only a column. The disc lands in the lowest free cell of that column.
  • Strict Turn Order: Players alternate, and a rejected move never consumes or skips a turn.
  • Win and Draw Detection: After every accepted move the game reports a win for N or more discs in a row (horizontal, vertical, or either diagonal), or a draw when the board is full with no winner.
  • Invalid Move Handling: A wrong turn, a column outside the board, a full column, and a move after the game ended all come back as a MoveResult value and leave the game untouched.
  • Atomic Moves: Two clients can submit moves for the same game at the same moment without corrupting the board or the turn order.

Explicit Boundaries (Out-of-Scope)

  • No AI Opponent: Both seats are driven by callers. A computer player is an extension that plugs in as another caller.
  • No Undo or Move History: The game only holds the current position, not the list of moves that produced it.
  • No Networking or Persistence: Games live in memory, and matchmaking, timers and rendering beyond plain text are not modelled.

Class Diagram & Entity Relationships

The game owns the board, the player list, the win rule, and the lock that makes every move atomic. The board knows only gravity and cell contents, while the win rule knows only how to recognize a line. Every field and method below mirrors the Java blueprint, and the TypeScript and Python versions follow the same structure in their own idioms.

Loading...
  • Gravity lives in the board: Board.drop reads heights[col] to find the lowest free row in constant time, and it returns -1 for a full column instead of throwing, because a full column is an ordinary outcome of a player’s choice.
  • One seam for the win rule: WinRule receives the board and the landing cell, so the optimized rule can start from the new disc while the baseline rule can ignore the cell and rescan.
  • Results are values: MoveResult names every way a call can end, and GameStatus records only where the game stands. Keeping them apart lets a rejected move report why without changing the status.

Design Patterns & SOLID Principles

  • Strategy Pattern (Win Rules):Game holds a WinRule and calls isWin(board, row, col) after every drop. LineWinRule and FullScanWinRule are two real implementations of that interface, so the rule is chosen at construction time and the game loop never changes. The driver relies on this seam to replay random games with both rules and check that they agree on every move.
  • Value Object (Disc and Player):Disc is immutable and compares by its symbol, and Player pairs a name with one Disc. Game decides whose turn it is by comparing discs, and its constructor rejects two players who share a disc.
  • Single Responsibility Principle (SRP):Board owns gravity and cell contents, WinRule implementations own line recognition, and Game owns turn order, status and the lock. A new win rule never touches the board, and a new board size never touches the rules.

Patterns this design deliberately does not use

GameStatus is a plain enum, not the State pattern. Only makeMove behaves differently by status, and it does so with one early return, so three state objects would add ceremony without removing a branch. The State pattern earns its place when each status carries its own behavior, for example a paused game that accepts a different set of calls. There is also no Singleton, because every match is its own Game with its own lock.

Algorithm: Constant-Time Win Check Around the Last Disc

Baseline: rescan the whole board after every move

The obvious win check visits every occupied cell and, for each of the four line directions, looks at the next N - 1 cells to see whether the same disc continues. That is what FullScanWinRule does. On the classic 6 by 7 board it starts from up to 42 cells and reads up to 42 x 4 x 3 = 504 neighbors per move, and the work grows with the board area as O(R x C x N). It is correct and easy to explain, which is why the blueprint keeps it as an oracle.

Optimized: count outward from the disc that just landed

The board had no winning line before this move, otherwise the game would already be over. So any new winning line must pass through the disc that just landed, and nothing else on the board needs to be read. LineWinRule takes the landing cell and, for each of the four directions (horizontal, vertical, ascending diagonal and descending diagonal), counts matching discs outward in both directions. The line length is 1 + forward + backward, and the player wins when it reaches N.

Each outward walk stops after N - 1 matches, because more than that cannot change the answer. A walk therefore reads at most N - 1 cells, since it either stops on a mismatch or an edge, or stops at the cap without looking further. That gives at most 2 x (N - 1) cells per direction and 8 x (N - 1) across all four, which is 6 and 24 for Connect Four. The cost depends on N and not on the board size, so it is constant for a fixed rule.

Worked trace: the winning move of the driver game

In the first driver scenario Alice drops into column 3 and the disc lands on row 3, on top of three discs. The check reads 8 cells in total before it returns true.

  1. Horizontal: the cells at columns 4 and 2 on row 3 are empty, so the line length is 1.
  2. Vertical: the cell above is empty and the cell below belongs to Bob, so the line length is 1.
  3. Ascending diagonal: the cell up and to the right is empty, while down and to the left holds three of Alice’s discs. The walk stops at its cap of 3, so the length is 1 + 0 + 3 = 4 and Alice wins.

Gravity and draw detection

Finding where a disc lands is also constant time, because heights[col] already holds the lowest free row, so no column scan is needed. A draw is detected with a counter. After a move that did not win, the game compares discCount with rows x cols, and win is checked first because the very last disc on a full board can still complete a line.

  • Baseline win check: O(R x C x N) per move.
  • Line win check: O(N) per move with at most 8 x (N - 1) cell reads, which is O(1) for a fixed N and independent of the board size.
  • Drop and draw check: O(1) each.

Follow-up: bitboards for a game-playing AI

A minimax search evaluates millions of positions, so walking cells one by one becomes the bottleneck. The standard encoding keeps each player’s discs in a single 64-bit integer with 7 bits per column, which is 6 rows plus one empty sentinel bit that stops a line from wrapping between columns. A four-in-a-row test in one direction is then m = b & (b >> s) followed by (m & (m >> 2 * s)) != 0, where the shift s is 1 for vertical, 7 for horizontal, and 6 or 8 for the two diagonals. Placing and undoing a disc are single bit operations as well. The blueprint does not implement it because it hides the board model that an interview is really about, and the grid version is more than fast enough for human play.

Core Execution Workflows

1. Creating a Game

  1. The caller builds new Game(6, 7, [alice, bob], new LineWinRule(4)), which fixes the rows, the columns, the players and the win rule.
  2. The constructors reject fewer than two players, two players sharing a disc, a board with a non-positive size, and a win rule with a connect length below 2. These are programming errors, so they throw instead of returning a MoveResult.
  3. The board starts empty with every column height at 0, the status is IN_PROGRESS, and the first player in the list moves first.

2. Making a Move

  1. A client calls makeMove(player, col) and the game takes its lock (in Java and Python, while TypeScript relies on its single-threaded event loop).
  2. If the status is not IN_PROGRESS, return GAME_OVER.
  3. If the caller’s disc is not the disc of the player whose turn it is, return WRONG_TURN.
  4. If the column is outside the board, return INVALID_COLUMN.
  5. Call board.drop(col, disc):
    1. If the column is full, drop returns -1 without changing anything and the game returns COLUMN_FULL.
    2. Otherwise the disc is stored at heights[col], the height and the disc count each grow by one, and the landing row is returned.
  6. Ask the win rule whether the disc at the landing cell completes a line. If it does, set the status to WON, record the winner and return WON without advancing the turn.
  7. Otherwise, if the disc count equals rows times columns, set the status to DRAW and return DRAW.
  8. Otherwise advance the turn to the next player, return PLACED, and release the lock.

Every rejection in steps 2 to 5 returns before the board changes, so a rejected move never costs the player their turn.

3. Two Clients Submit at the Same Moment

  1. Two requests for the same player and column reach the game together, for example a double click or an impatient retry.
  2. One request takes the lock first and runs the whole of workflow 2. The disc lands and the turn moves to the other player.
  3. The second request takes the lock next and fails the turn check, so it returns WRONG_TURN and the board is unchanged.
  4. If the two requests come from different players, whichever takes the lock first decides the outcome. A request from the player who is not on turn is rejected with WRONG_TURN and the client must resubmit after it sees the other move.

Concurrency & Thread Safety Strategy

Shared mutable state

One game has six pieces of mutable state: Board.grid, Board.heights, Board.discCount, Game.turn, Game.status and Game.winner. A single move reads and writes all of them, so the unit that has to be atomic is the whole move and not any one field.

The races

  • Double submit: Alice’s client sends column 3 twice at once. Both requests read that it is Alice’s turn and both drop a disc, so Alice gets two discs for one turn and Bob’s turn is skipped or the turn counter is left wrong.
  • Lost update on a column: two drops read heights[3] == 2 at the same moment and both write to row 2. One disc overwrites the other, and the height and the disc count no longer match what is on the board.
  • Stale game over check: Bob’s request reads IN_PROGRESS just before Alice’s winning move sets WON, so Bob drops a disc into a finished game, or both threads write the winner and the last write wins.

The guard and where it sits

In Java, Game holds one ReentrantLock and makeMove takes it before the first check and releases it in a finally block after the last write. The read methods status, winner, discCount and render take the same lock, so a reader never sees a half-applied move. In Python, Game holds a threading.Lock and wraps the same span in a with block, which is still required because the check and the write span many bytecodes and the interpreter lock does not make them one step. In TypeScript there is no lock. Node runs one task to completion before starting the next, and makeMove contains no await, so no other request can run in the middle of it. The driver’s two simultaneous makeMove calls on one game are an async stand-in for this race.

One lock per game covers the whole move because the turn and the status are game-wide, so a lock per column would protect heights but not the turn check. The board is created inside Game and never handed out, which makes the game lock the only door to it. The critical section is a handful of assignments plus at most 24 cell reads, so it is held for microseconds, and since every game has its own lock, separate matches never contend.

What the guard does not cover

  • More than one process: the lock lives in one process. If two servers each hold a copy of the game, they do not coordinate. Production routes every move for a game id to a single owner, or stores the position in a database row and applies each move as UPDATE ... WHERE id = ? AND version = ? so that a stale writer fails and refetches.
  • Retries: a client that times out and resends a move cannot be told apart from a new move once the turn has come back around. A real API sends a move number or an idempotency key and treats a repeat of an applied move as already done.
  • Check-then-act in the caller: reading status() and then calling makeMove is two steps with a gap between them. Callers should act on the returned MoveResult and not on a pre-check.

A test that exposes a broken guard

Release two threads at the same instant with a barrier, have both submit the same player’s move into the same column, and assert that the results are exactly one PLACED and one WRONG_TURN and that the board holds one disc. Repeat it over many fresh games. The Java and Python drivers do this over 1000 rounds, and the TypeScript driver does it with two simultaneous async submissions. In a trial run with the lock removed from the Java blueprint, a few of the 1000 rounds failed, so the test needs many rounds to catch a missing guard.

Complete Clean Code Blueprint

Reference implementations of the board, the two win rules and the lock-guarded game in Java, TypeScript, and Python. Each driver plays a diagonal win, rejects invalid moves, draws on a small board, replays random games against both win rules, and races two simultaneous submissions.

// ─── JAVA BLUEPRINT ──────────────────────────────────────────────────────────
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

record Disc(char symbol) {}

record Player(String name, Disc disc) {}

enum GameStatus { IN_PROGRESS, WON, DRAW }

enum MoveResult { PLACED, WON, DRAW, WRONG_TURN, INVALID_COLUMN, COLUMN_FULL, GAME_OVER }

class Board {
    private final int rows;
    private final int cols;
    private final Disc[][] grid;   // grid[row][col], row 0 is the bottom row
    private final int[] heights;   // next free row in each column
    private int discCount = 0;

    Board(int rows, int cols) {
        if (rows < 1 || cols < 1) throw new IllegalArgumentException("Board needs at least one row and one column");
        this.rows = rows;
        this.cols = cols;
        this.grid = new Disc[rows][cols];
        this.heights = new int[cols];
    }

    int rows() { return rows; }
    int cols() { return cols; }
    int discCount() { return discCount; }
    boolean isFull() { return discCount == rows * cols; }
    boolean isValidColumn(int col) { return col >= 0 && col < cols; }
    boolean inBounds(int row, int col) { return row >= 0 && row < rows && col >= 0 && col < cols; }
    Disc discAt(int row, int col) { return grid[row][col]; }

    // Gravity: the disc lands in the lowest free cell. Returns that row, or -1 when the column is full.
    int drop(int col, Disc disc) {
        if (heights[col] == rows) return -1;
        int row = heights[col]++;
        grid[row][col] = disc;
        discCount++;
        return row;
    }

    List<String> render() {
        List<String> lines = new ArrayList<>();
        for (int r = rows - 1; r >= 0; r--) {
            StringBuilder line = new StringBuilder("|");
            for (int c = 0; c < cols; c++) {
                line.append(' ').append(grid[r][c] == null ? '.' : grid[r][c].symbol());
            }
            lines.add(line.append(" |").toString());
        }
        StringBuilder footer = new StringBuilder(" ");
        for (int c = 0; c < cols; c++) footer.append(' ').append(c % 10);
        lines.add(footer.toString());
        return lines;
    }
}

interface WinRule {
    // True when the disc at (row, col), just dropped, completes a winning line.
    boolean isWin(Board board, int row, int col);
}

// Optimized rule: only the four lines through the new disc can hold a new win.
class LineWinRule implements WinRule {
    private static final int[][] DIRECTIONS = {{0, 1}, {1, 0}, {1, 1}, {1, -1}};
    private final int connect;

    LineWinRule(int connect) {
        if (connect < 2) throw new IllegalArgumentException("connect must be at least 2");
        this.connect = connect;
    }

    public boolean isWin(Board board, int row, int col) {
        Disc disc = board.discAt(row, col);
        if (disc == null) return false;
        for (int[] d : DIRECTIONS) {
            int line = 1 + run(board, row, col, d[0], d[1], disc) + run(board, row, col, -d[0], -d[1], disc);
            if (line >= connect) return true;
        }
        return false;
    }

    // Counts matching discs outward from (row, col), stopping after connect - 1 of them.
    private int run(Board board, int row, int col, int dr, int dc, Disc disc) {
        int count = 0;
        int r = row + dr;
        int c = col + dc;
        while (count < connect - 1 && board.inBounds(r, c) && disc.equals(board.discAt(r, c))) {
            count++;
            r += dr;
            c += dc;
        }
        return count;
    }
}

// Baseline rule: rescans every cell and ignores the last move. Kept independent of LineWinRule on purpose,
// so the driver can use it as an oracle for the optimized rule.
class FullScanWinRule implements WinRule {
    private static final int[][] FORWARD = {{0, 1}, {1, 0}, {1, 1}, {1, -1}};
    private final int connect;

    FullScanWinRule(int connect) {
        if (connect < 2) throw new IllegalArgumentException("connect must be at least 2");
        this.connect = connect;
    }

    public boolean isWin(Board board, int row, int col) {
        for (int r = 0; r < board.rows(); r++) {
            for (int c = 0; c < board.cols(); c++) {
                Disc disc = board.discAt(r, c);
                if (disc == null) continue;
                for (int[] d : FORWARD) {
                    if (startsRun(board, r, c, d[0], d[1], disc)) return true;
                }
            }
        }
        return false;
    }

    private boolean startsRun(Board board, int r, int c, int dr, int dc, Disc disc) {
        for (int step = 1; step < connect; step++) {
            int nr = r + dr * step;
            int nc = c + dc * step;
            if (!board.inBounds(nr, nc) || !disc.equals(board.discAt(nr, nc))) return false;
        }
        return true;
    }
}

class Game {
    private final Board board;
    private final List<Player> players;
    private final WinRule winRule;
    private final ReentrantLock lock = new ReentrantLock();
    private int turn = 0;
    private GameStatus status = GameStatus.IN_PROGRESS;
    private Player winner = null;

    Game(int rows, int cols, List<Player> players, WinRule winRule) {
        if (players.size() < 2) throw new IllegalArgumentException("Need at least two players");
        Set<Disc> discs = new HashSet<>();
        for (Player p : players) {
            if (!discs.add(p.disc())) throw new IllegalArgumentException("Each player needs a distinct disc");
        }
        this.board = new Board(rows, cols);
        this.players = List.copyOf(players);
        this.winRule = winRule;
    }

    // One move is one critical section: turn check, drop, win check and turn advance happen under the lock.
    MoveResult makeMove(Player player, int col) {
        lock.lock();
        try {
            if (status != GameStatus.IN_PROGRESS) return MoveResult.GAME_OVER;
            if (!players.get(turn).disc().equals(player.disc())) return MoveResult.WRONG_TURN;
            if (!board.isValidColumn(col)) return MoveResult.INVALID_COLUMN;
            int row = board.drop(col, player.disc());
            if (row < 0) return MoveResult.COLUMN_FULL;
            if (winRule.isWin(board, row, col)) {
                status = GameStatus.WON;
                winner = player;
                return MoveResult.WON;
            }
            if (board.isFull()) {
                status = GameStatus.DRAW;
                return MoveResult.DRAW;
            }
            turn = (turn + 1) % players.size();
            return MoveResult.PLACED;
        } finally {
            lock.unlock();
        }
    }

    GameStatus status() {
        lock.lock();
        try { return status; } finally { lock.unlock(); }
    }

    Optional<Player> winner() {
        lock.lock();
        try { return Optional.ofNullable(winner); } finally { lock.unlock(); }
    }

    int discCount() {
        lock.lock();
        try { return board.discCount(); } finally { lock.unlock(); }
    }

    List<String> render() {
        lock.lock();
        try { return board.render(); } finally { lock.unlock(); }
    }
}

public class Main {
    private static final Player ALICE = new Player("Alice", new Disc('X'));
    private static final Player BOB = new Player("Bob", new Disc('O'));
    private static final List<Player> PLAYERS = List.of(ALICE, BOB);
    private static long seed = 42;

    // Park-Miller generator, so the TypeScript and Python drivers replay the same random games.
    private static int nextInt(int bound) {
        seed = seed * 48271 % 2147483647;
        return (int) (seed % bound);
    }

    // Alice moves first and the players alternate through the given columns.
    private static List<MoveResult> play(Game game, int... columns) {
        List<MoveResult> results = new ArrayList<>();
        for (int i = 0; i < columns.length; i++) {
            results.add(game.makeMove(i % 2 == 0 ? ALICE : BOB, columns[i]));
        }
        return results;
    }

    private static void differential(int rows, int cols, int connect, int games) {
        int moves = 0, wins = 0, draws = 0;
        boolean agreed = true;
        for (int g = 0; g < games; g++) {
            Game fast = new Game(rows, cols, PLAYERS, new LineWinRule(connect));
            Game slow = new Game(rows, cols, PLAYERS, new FullScanWinRule(connect));
            Player current = ALICE;
            while (fast.status() == GameStatus.IN_PROGRESS) {
                int col = nextInt(cols);
                MoveResult a = fast.makeMove(current, col);
                MoveResult b = slow.makeMove(current, col);
                if (a != b) agreed = false;
                if (a != MoveResult.COLUMN_FULL) moves++;
                if (a == MoveResult.PLACED) current = current.equals(ALICE) ? BOB : ALICE;
            }
            if (fast.status() == GameStatus.WON) wins++; else draws++;
        }
        System.out.println(rows + " rows x " + cols + " cols, connect " + connect + ": " + games + " random games, "
            + moves + " moves, " + wins + " wins, " + draws + " draws, both rules agreed on every move: " + agreed);
    }

    private static void raceTwoSubmissions(int rounds) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        int clean = 0;
        for (int i = 0; i < rounds; i++) {
            Game game = new Game(6, 7, PLAYERS, new LineWinRule(4));
            CyclicBarrier start = new CyclicBarrier(2);
            Callable<MoveResult> submit = () -> {
                start.await();
                return game.makeMove(ALICE, 3);
            };
            Future<MoveResult> first = pool.submit(submit);
            Future<MoveResult> second = pool.submit(submit);
            List<MoveResult> outcomes = new ArrayList<>(List.of(first.get(), second.get()));
            Collections.sort(outcomes);
            if (outcomes.equals(List.of(MoveResult.PLACED, MoveResult.WRONG_TURN)) && game.discCount() == 1) clean++;
        }
        pool.shutdown();
        System.out.println("Alice double-submits column 3, " + rounds + " rounds: " + clean
            + " had exactly one PLACED, one WRONG_TURN and one disc on the board");
    }

    public static void main(String[] args) throws Exception {
        System.out.println("=== 1. Classic 7x6 game, Alice wins on a diagonal ===");
        Game game = new Game(6, 7, PLAYERS, new LineWinRule(4));
        List<MoveResult> results = play(game, 0, 1, 1, 2, 3, 2, 2, 3, 6, 3, 3);
        game.render().forEach(System.out::println);
        System.out.println("Last move: " + results.get(results.size() - 1) + ", status: " + game.status()
            + ", winner: " + game.winner().map(Player::name).orElse("none"));
        System.out.println("Bob tries column 4 afterwards: " + game.makeMove(BOB, 4));

        System.out.println("=== 2. Rejected moves leave the game untouched ===");
        Game g2 = new Game(6, 7, PLAYERS, new LineWinRule(4));
        System.out.println("Bob moves first: " + g2.makeMove(BOB, 3));
        System.out.println("Alice picks column 7: " + g2.makeMove(ALICE, 7));
        play(g2, 0, 0, 0, 0, 0, 0);
        System.out.println("Alice drops into the full column 0: " + g2.makeMove(ALICE, 0));
        System.out.println("Alice retries in column 1: " + g2.makeMove(ALICE, 1) + ", discs on board: " + g2.discCount());

        System.out.println("=== 3. A draw on a 2x3 board with connect 3 ===");
        Game g3 = new Game(2, 3, PLAYERS, new LineWinRule(3));
        System.out.println(play(g3, 0, 1, 2, 0, 1, 2) + ", status: " + g3.status());

        System.out.println("=== 4. Optimized rule versus full scan on random games ===");
        differential(6, 7, 4, 200);
        differential(5, 5, 3, 200);

        System.out.println("=== 5. Two clients submit at the same moment ===");
        raceTwoSubmissions(1000);
    }
}

πŸ’¬Review

Help Us Improve

How helpful was this walkthrough?

Click a star to rate. We actively use this feedback to refine and update our system design content.

Placeholder
Optional but highly appreciated!

Discussion

Share your thoughts, ask questions, or help others.

Loading comments...