How to approach an LLD interview, including UML, errors and testing

A low-level design (LLD) interview asks you to design the classes inside one component, for example a parking lot, a chess game or a booking system, and then write real code for the core of it. Unlike the high-level design (HLD) round, which is about servers and scale, it is about clean objects, correct rules and code that is easy to change. This lesson gives a repeatable way to run the 45 minutes, the UML you need, how to handle errors, and how to test, using Snake and Ladder as the example.

1. What the Interviewer Is Judging

  • Requirements: did you ask before building, and state your assumptions?
  • Modeling: are the classes the right ones, with one clear job each?
  • Code quality: readable names, rules in one place, code that compiles and runs.
  • Correctness: do you think about edge cases, bad input and invalid states?
  • Extensibility: when they say "now add X", does the change touch one place?
  • Communication: do you think aloud and take hints?

Nobody checks how many patterns you used. Using none beats forcing one. SOLID and the patterns have their own lessons. Here we focus on the process.

2. The Seven Steps and a Time Budget

Step Minutes (of 45) What you produce
1. Clarify requirements 5 Features in scope, rules, assumptions, what is out
2. Find entities and actions 5 List of classes (nouns) and operations (verbs)
3. Draw the class diagram 5 Classes, relationships, interfaces
4. Define the public API 3 Method signatures of the main class
5. Walk the core flow 2 What happens, step by step, for the main use case
6. Write the code 18 Working core classes in Java
7. Edge cases and tests 7 Error handling, 3 to 4 tests, one extension ("now add X")

Do not start coding at minute 1. Do not spend 25 minutes on diagrams either. The code is the main deliverable.

2.1 Clarify Requirements (Step 1)

Ask short questions that change the design. For Snake and Ladder:

  • How many players? 2 to 4.
  • Board size and layout? 100 cells, snakes and ladders configured at start.
  • How is the dice rolled? One six-sided dice.
  • What if the roll goes past 100? Reaching 100 or more wins the game.
  • Can a snake or ladder start on cell 100, or chain into another one? No. We reject both when the board is built, and also any board where the last cell can never be reached.
  • Out of scope? UI, network play, saving games.

Say the answers back as a list of assumptions.

2.2 Find Entities and Actions (Step 2)

Underline the nouns in the requirements. They become candidate classes: game, board, player, dice, snake, ladder. Underline the verbs. They become methods: roll, move, take a turn, win. Keep a noun as a class only if it has its own data and rules.

  • A snake and a ladder are the same thing seen from two sides: "if you land on cell A, go to cell B". One record, SnakeOrLadder, covers both. A snake is one where the end is lower.
  • Dice is a class with behavior (roll), and it must be replaceable in tests, so it becomes an interface.
  • The turn order and the winner belong to Game. The movement rule (add the roll, apply a snake or ladder, handle going past the end) belongs to Board, because it depends on the board's data.

3. UML You Actually Need

UML is a standard way to draw designs. In an interview you need two diagrams. The class diagram is the main one (step 3). A sequence diagram is optional and shows one flow over time. Simple boxes are enough.

3.1 The Class Diagram (Step 3)

classDiagram
    class Game {
        -Deque~Player~ turns
        -Player winner
        +takeTurn() TurnResult
        +winner() Optional~Player~
    }
    class Board {
        -int size
        +move(int position, int roll) int
        +isLastCell(int position) boolean
    }
    class SnakeOrLadder {
        <<record>>
        +int from
        +int to
    }
    class Player {
        -String name
        -int position
        +moveTo(int position)
    }
    class Dice {
        <<interface>>
        +roll() int
    }
    class RandomDice
    class TurnResult
    Game "1" --> "1" Board
    Game "1" --> "1" Dice
    Game "1" o-- "2..4" Player
    Board "1" *-- "0..*" SnakeOrLadder
    RandomDice ..|> Dice
    Game ..> TurnResult
Relationship Meaning Arrow Example above
Association Knows about, uses solid line with arrow Game uses Dice
Aggregation Has, parts can live on their own open diamond Game has Players
Composition Owns, parts die with the owner filled diamond Board owns its snakes and ladders
Inheritance Is a kind of solid line, hollow triangle none here
Realization Implements an interface dashed line, hollow triangle RandomDice implements Dice
Dependency Uses briefly, only as a parameter or return value dashed arrow Game returns TurnResult

Write multiplicity on the lines ("1", "2..4", "0..*"). It answers questions like "can a game have one player?" without words. Prefer composition and association over inheritance. Use inheritance only for a true "is a" relationship with the same behavior contract.

3.2 API and Core Flow (Steps 4 and 5)

Write the main class's public methods first: Game(board, players, dice), takeTurn() and winner(). Then say the flow of one turn in five lines: take the next player, roll the dice, ask the board where that player ends up, move the player, and if that is the last cell they win. Otherwise they go to the back of the queue.

4. Writing the Code

// One class covers both snakes and ladders: land on "from", move to "to".
record SnakeOrLadder(int from, int to) {
}

class Board {
    private static final int MAX_ROLL = 6;

    private final Map<Integer, Integer> jumpTargets = new HashMap<>();
    private final int size;

    public Board(int size, List<SnakeOrLadder> snakeOrLadders) {
        if (size < 2) {
            throw new IllegalArgumentException("Board too small: " + size);
        }
        this.size = size;

        for (SnakeOrLadder jump : snakeOrLadders) {
            if (jump.from() < 1 || jump.from() >= size || jump.to() < 1 || jump.to() > size || jump.from() == jump.to()) {
                throw new IllegalArgumentException("Invalid SnakeOrLadder: " + jump);
            }
            if (jumpTargets.put(jump.from(), jump.to()) != null) {
                throw new IllegalArgumentException("Two jumps start at " + jump.from());
            }
        }

        for (int target : jumpTargets.values()) {
            if (jumpTargets.containsKey(target)) {
                throw new IllegalArgumentException("Jump chain at cell " + target);
            }
        }

        if (!lastCellReachable()) {
            throw new IllegalArgumentException("The last cell can never be reached");
        }
    }

    // The movement rule lives here: add the roll, reaching or passing
    // the last cell ends at the last cell, otherwise apply a snake or ladder.
    public int move(int position, int roll) {
        int target = position + roll;
        if (target >= size) {
            return size;
        }
        return jumpTargets.getOrDefault(target, target);
    }

    public boolean isLastCell(int position) {
        return position >= size;
    }

    // Breadth-first search from cell 0: can any sequence of rolls finish the game?
    private boolean lastCellReachable() {
        Set<Integer> seen = new HashSet<>(Set.of(0));
        Deque<Integer> queue = new ArrayDeque<>(List.of(0));

        while (!queue.isEmpty()) {
            int position = queue.poll();
            for (int roll = 1; roll <= MAX_ROLL; roll++) {
                int next = move(position, roll);
                if (isLastCell(next)) {
                    return true;
                }
                if (seen.add(next)) {
                    queue.add(next);
                }
            }
        }
        return false;
    }
}

interface Dice {
    int roll();
}

class RandomDice implements Dice {
    private final Random random = new Random();

    @Override
    public int roll() {
        return random.nextInt(6) + 1;
    }
}

class Player {
    private final String name;
    private int position;

    Player(String name) {
        this.name = name;
        this.position = 0;
    }

    public String name() {
        return name;
    }

    public int position() {
        return position;
    }

    // Package-private: only Game moves players.
    void moveTo(int position) {
        this.position = position;
    }
}

// What happened in one turn, so the caller decides how to show it.
record TurnResult(String playerName, int roll, int from, int to) {
}

class Game {
    private final Board board;
    private final Dice dice;
    private final Deque<Player> turns;
    private Player winner;

    Game(Board board, List<Player> players, Dice dice) {
        if (board == null || dice == null) {
            throw new IllegalArgumentException("Board and dice are required");
        }
        if (players == null || players.size() < 2 || players.size() > 4) {
            throw new IllegalArgumentException("Need 2 to 4 players");
        }
        Set<String> names = new HashSet<>();
        for (Player player : players) {
            if (player == null || !names.add(player.name())) {
                throw new IllegalArgumentException("Players must be present and have different names");
            }
        }
        this.board = board;
        this.dice = dice;
        this.turns = new ArrayDeque<>(players);
    }

    public TurnResult takeTurn() {
        if (winner != null) {
            throw new IllegalStateException("Game is over");
        }

        int roll = dice.roll();
        if (roll < 1 || roll > 6) {
            throw new IllegalStateException("Dice returned " + roll);
        }

        Player player = turns.pollFirst();
        int from = player.position();
        int to = board.move(from, roll);
        player.moveTo(to);

        if (board.isLastCell(to)) {
            winner = player;
        } else {
            turns.addLast(player);
        }
        return new TurnResult(player.name(), roll, from, to);
    }

    public Optional<Player> winner() {
        return Optional.ofNullable(winner);
    }
}

The entry point plays turns on a 100-cell board until someone wins:

public static void main(String[] args) {
    Board board = new Board(100, List.of(
            new SnakeOrLadder(10, 20),
            new SnakeOrLadder(30, 40),
            new SnakeOrLadder(50, 80),
            new SnakeOrLadder(90, 11),
            new SnakeOrLadder(51, 9),
            new SnakeOrLadder(31, 2)));

    Game game = new Game(board, List.of(new Player("A"), new Player("B")), new RandomDice());

    while (game.winner().isEmpty()) {
        TurnResult turn = game.takeTurn();
        System.out.println(turn.playerName() + " rolled " + turn.roll()
                + ": " + turn.from() + " -> " + turn.to());
    }
    System.out.println("Winner: " + game.winner().get().name());
}

It prints one line per turn, such as A rolled 2: 98 -> 100, then Winner: A.

Things to say while writing:

  • The dice is injected through the constructor. That is dependency injection, and it is what makes the game testable.
  • Each rule lives in one place: the movement rule in Board, the turn order and winner in Game. If the overshoot rule changes, only Board.move changes.
  • The game keeps its own state. takeTurn() moves one step and remembers the winner, so a test can stop at any turn. It returns a TurnResult instead of printing, and main decides how to show it.

5. Handling Errors

Interviewers watch for this. A simple rule works well:

  • Broken contracts throw exceptions. Bad input is IllegalArgumentException. A call in the wrong state is IllegalStateException. In the code above: a bad board (too small, a jump chain, two jumps from one cell, or a board nobody can win, found by a search in the constructor), a game with one player or no dice, and takeTurn() after someone has won.
  • Expected business outcomes are returned, not thrown. "A player went past the last cell" is normal play, so takeTurn() returns a result. In a booking system, "seat already taken" should be a result or a specific exception that callers handle, not a crash.
  • Fail fast, validate at the edge. Check input in constructors and public methods, so a bad value never travels deep into the code.
  • Make illegal states hard to represent. Use enums, records with checks and private fields. Return Optional, not null or -1.
  • Use a custom exception (for example InsufficientBalanceException) only when the caller must react differently to it. Prefer unchecked ones (see the note).
  • Never swallow errors with an empty catch. Either handle it, or let it go up with the original cause attached.
Background note: Checked and unchecked exceptions in Java

A checked exception (such as IOException) must be declared or caught, so the compiler forces every caller to deal with it. An unchecked exception (a subclass of RuntimeException, such as IllegalArgumentException) needs no declaration. In an interview, use unchecked exceptions for broken contracts and programming errors, and a checked one only when the caller can realistically recover. Many teams and frameworks such as Spring prefer unchecked exceptions, because checked ones clutter every signature and do not work well inside lambdas.

6. Testing in the Interview

You do not write a full test suite in 45 minutes. Write three or four tests for the most important rules, and say what else you would test. Because the dice is an interface, a test supplies a scripted dice with fixed rolls, so there is no randomness.

class ScriptedDice implements Dice {
    private final Iterator<Integer> rolls;
    ScriptedDice(Integer... values) { this.rolls = List.of(values).iterator(); }
    public int roll() { return rolls.next(); }
}

class GameTest {
    private final Player a = new Player("A");
    private final Player b = new Player("B");

    private Game game(int size, List<SnakeOrLadder> jumps, Integer... rolls) {
        return new Game(new Board(size, jumps), List.of(a, b), new ScriptedDice(rolls));
    }

    @Test
    void ladderMovesPlayerUp() {
        TurnResult t = game(100, List.of(new SnakeOrLadder(3, 22)), 3).takeTurn();
        assertEquals(22, t.to());
    }

    @Test
    void overshootWinsAndStopsOnTheLastCell() {
        Game g = game(10, List.of(), 6, 1, 6);        // A: 6, B: 1, A: 12 -> 10
        g.takeTurn(); g.takeTurn();
        assertEquals(10, g.takeTurn().to());
        assertSame(a, g.winner().orElseThrow());
    }

    @Test
    void duplicateStartIsRejected() {
        assertThrows(IllegalArgumentException.class, () -> new Board(10,
                List.of(new SnakeOrLadder(3, 5), new SnakeOrLadder(3, 7))));
    }
}

What to say about testing:

  • Test behavior through public methods, not internals.
  • Prefer a simple fake (the scripted dice) over a mocking framework. It is clearer and survives refactoring.
  • Cover edges: landing exactly on the last cell, a jump chain, a board nobody can win, a dice that returns 0 or 7, one player, duplicate names, and a game played after it ended.

7. The "Now Add X" Round

The last few minutes are usually an extension. Name where the change goes before you touch code.

  • Two dice or a loaded dice: a new Dice class. Nothing else changes.
  • Exact landing, or bounce back: pull the rule out of Game into a strategy object. This is the Strategy pattern, and it is only worth doing now because a second rule exists.
  • Undo, history: store each move and the previous position. That points to the Command pattern.
  • Many games at once on a server: each Game is separate. Concurrent calls on one game need a lock or a single thread per game (see the concurrency lesson).

The answer to every extension is the same: "It goes here, and these classes stay unchanged".

8. Common Pitfalls

  • Jumping to code without clarifying requirements or stating assumptions.
  • A class per noun with no behavior (only getters and setters), and all rules in one Manager class.
  • Separate Snake and Ladder classes with copied logic, instead of seeing they are the same idea.
  • Printing inside domain classes. It makes them hard to test and to reuse. Return a result instead.
  • A game that runs in one call with no state. It cannot be stepped, resumed or protected from being played twice.
  • Loops that may never end, such as a dice that returns 0 or a board nobody can win. Reject them first.
  • Sharing one Player object between two games. The position is stored in it, so the games would interfere.
  • Hidden dependencies, such as new Random() inside the game, so nothing can be tested.

9. Interview Questions This Lesson Prepares You For

  • How do you start an LLD interview? I ask 4 to 6 questions about scope, rules and edge cases, then repeat my assumptions as a short list. Then I list entities and actions, sketch a small class diagram, agree the main API, and only then write code.
  • How do you decide what the classes are? Take the nouns as candidates and keep one as a class only if it has its own data and rules. Merge things that behave the same (snake and ladder are one record). Give each rule to the class that owns the data it needs.
  • Which UML diagrams do you draw and how detailed? A class diagram with the main classes, key methods, relationships and multiplicity. A sequence diagram only if a flow is hard to explain in words. Clarity matters more than perfect notation.
  • How do you handle errors in your design? Validate input where it enters and fail fast with clear exceptions. Use IllegalArgumentException for bad input and IllegalStateException for wrong-state calls. Return results for normal business outcomes, such as "seat taken". Avoid null and error codes, never swallow exceptions, and make illegal states impossible to build.
  • How do you make your design testable? Inject dependencies and hide randomness, time and I/O behind interfaces, so a test passes a fake, such as a scripted dice or a fixed clock.
  • The interviewer says "add feature X". What do you do? First say which classes change and which stay the same. If the design is sound, it should be one new class or one changed rule. If the change forces edits everywhere, say so and explain how you would refactor.
  • When should you use a design pattern in an LLD interview? When there is a real second variant or a clear repeated problem, such as several pricing rules (Strategy) or an object with a lifecycle (State). Explain the problem first, then name the pattern. A simple design with no patterns beats a complex one with many.