More interview problems · Chapter 25

How to approach an LLD interview

A step-by-step method for low-level design interviews: OOD discussion vs machine coding, timings, finding classes, choosing patterns, clean code, tests and concurrency.

IntermediateInterview priority: High50 min
On this page
  1. The problem: a blank editor and one vague sentence
  2. Two formats, two different jobs
  3. The method, step by step
  4. The worked example: complete code
  5. Step 7 and beyond: concurrency
  6. What interviewers grade
  7. Common mistakes
  8. When not to follow the full method
  9. In the interview
  10. Quiz

The problem: a blank editor and one vague sentence

The interviewer says one sentence: "Design a system to book meeting rooms." A common first reaction is to start typing classes straight away. Twenty minutes later there is a Room class with eight getters, a BookingManager that does everything, no code that runs, and the interviewer asks: "What happens if two people book the same room at the same moment?" There is no time left to answer well.

The candidate knew enough to pass. What failed was the process: no agreed scope, no plan for the time, nothing running at the end. Low-level design (LLD) interviews test whether you can turn a vague request into a small, correct, extensible object model and working code. This page gives you a repeatable method for that, then applies it end to end to the meeting-room problem, with complete Java and Python code.

Two formats, two different jobs

"LLD interview" covers two rounds that look alike but are graded differently. Ask the recruiter which one you have.

Where the time goes in each format

OOD discussionMachine-coding round
Length45–60 minutes60–120 minutes (90 is typical)
WhereWhiteboard, shared doc or plain editorYour own IDE; code must compile and run
You produceRequirements, class diagram, key method bodies, discussion of extensionsA complete working program with a demo (a main or tests), often submitted afterwards
Interviewer's roleActive: asks questions and pushes on design choicesOften silent while you code, then reviews and asks for a change
Typical problemsParking lot, elevator, library, chessSplitwise, snake and ladder, rate limiter, LRU cache, cab booking
Biggest riskDrawing classes without explaining whyRunning out of time with nothing that runs

OOD means object-oriented design: modelling a problem as classes that hold data and behaviour. Many large tech companies use the discussion format; many product companies (especially in India's startup ecosystem) use machine coding. Some do a hybrid: 15 minutes of design, then 30 of code.

The method, step by step

The same seven steps work in both formats; only the time spent on each changes.

StepWhat you doOOD (45 min)Machine coding (90 min)
1. ClarifyAsk questions, write the agreed scope and what's out5 min10 min
2. EntitiesNouns → classes, verbs → methods5 min5 min
3. Class designResponsibilities, relationships, interfaces for what varies10–15 min10 min
4. Core flowsSignatures and bodies of the 2–3 main methods10–15 min(part of coding)
5. CodeModels → services → driver(key methods only)45–50 min
6. TestHappy path, edge cases, a concurrency test2 min (talk)10 min
7. ExtendAnswer "what if…" without rewriting5–10 min10 min

Say the plan out loud at the start: "I'll spend five minutes on requirements, sketch the classes, then code the booking flow first." Interviewers grade time management, and a stated plan lets them steer you early.

Step 1: clarify the requirements

Ask questions that change the design, not ones that only change the UI. For the meeting-room booker:

  • Scale and shape: how many rooms and buildings? (In-memory is fine for an interview; say you'd swap in a database.)
  • The core rule: can bookings overlap? Is 9:00–10:00 next to 10:00–11:00 allowed? (Yes: treat slots as half-open, [start, end), meaning the start is included and the end is not.)
  • Who can do what: can anyone cancel, or only the organiser?
  • Choice: does the user pick a room, or does the system pick one for a group size?
  • Concurrency: can two people book at once? (Always assume yes.)
  • Out of scope: recurring meetings, calendar invites, payments, UI.

Write the agreed list where the interviewer can see it. It becomes your checklist and your defence: when asked "what about recurring meetings?", you can say "out of scope, but here's how the design would absorb it".

Step 2: find the entities

Underline the nouns in the requirements. A noun that has its own data and behaviour becomes a class; a noun that only describes another one becomes a field; a noun nothing uses is dropped. Verbs become methods on the class that owns the data they change.

Nouns become classes or fields, then connect them

A useful test: "who owns this data?" The overlap check needs a room's bookings, so it lives next to them (in the service, per room), not in User. And small immutable concepts such as a time slot deserve their own value object: a tiny class compared by its contents, not its identity, that validates itself (start before end) and answers questions (overlaps). It removes a whole class of bugs from everywhere else.

Step 3: the class design

ClassResponsibilityWhy it exists
RoomId and capacityAn entity with identity
SlotStart, end, overlaps()Value object; one correct overlap rule
BookingWho booked which room for which slotThe record we create and cancel
BookingServiceBook, find a room, cancel; owns the locksThe one entry point for callers
RoomSelectionStrategyPicks one room from free candidatesThe rule most likely to change

Keep the number of classes small. Five well-named classes with clear jobs beat fifteen with vague ones. The only interface here is for the thing that varies: how to choose a room (smallest that fits, nearest to the user's desk, the one with a video screen).

Choosing patterns without forcing them

Interviewers reward patterns that solve a stated problem and penalise patterns used to show off. Name the signal first, then the pattern:

Signal in the requirementsPatternExample
"Several ways to do the same job, chosen at run time"StrategyPricing, room choice, split types, eviction
"Notify these people when X happens"ObserverHold ready, price alert, game over
"Behaviour depends on the current status, with rules for moving between them"StateVending machine, order lifecycle, elevator
"Undo", "queue requests", "log every action"CommandText editor, game moves
"Many optional parameters"BuilderA search query, a pizza order
"Create one of several types from input"FactoryVehicle from a type string

The worked example: complete code

The code below is what a strong 90-minute submission looks like for the agreed scope. Notice the order it is written in: models (value objects and entities, with validation), then the interface for what varies, then the service, then a driver that exercises every flow, including the edge cases and a race.

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

// ---------- models ----------
final class Room {
    private final String id;
    private final int capacity;
    Room(String id, int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException("capacity must be positive");
        this.id = id; this.capacity = capacity;
    }
    String id() { return id; }
    int capacity() { return capacity; }
}

/** A half-open time slot [start, end): a booking ending at 10:00 does not clash with one starting at 10:00. */
record Slot(LocalDateTime start, LocalDateTime end) {
    Slot {
        if (!start.isBefore(end)) throw new IllegalArgumentException("start must be before end");
    }
    boolean overlaps(Slot o) { return start.isBefore(o.end) && o.start.isBefore(end); }
}

record Booking(long id, String roomId, String userId, Slot slot) {}

class BookingConflictException extends RuntimeException {
    BookingConflictException(String msg) { super(msg); }
}

// ---------- what varies: how to pick a room ----------
interface RoomSelectionStrategy {
    /** Choose one room from candidates that are already free and big enough. */
    Optional<Room> choose(List<Room> candidates, int attendees);
}

class SmallestFitStrategy implements RoomSelectionStrategy {
    public Optional<Room> choose(List<Room> candidates, int attendees) {
        return candidates.stream().min(Comparator.comparingInt(Room::capacity));
    }
}

// ---------- the service ----------
class BookingService {
    private final Map<String, Room> rooms = new LinkedHashMap<>();          // filled at start-up only
    private final Map<String, List<Booking>> bookingsByRoom = new ConcurrentHashMap<>();
    private final Map<Long, Booking> bookingsById = new ConcurrentHashMap<>();
    private final AtomicLong nextId = new AtomicLong(1);
    private final RoomSelectionStrategy strategy;

    BookingService(RoomSelectionStrategy strategy) { this.strategy = Objects.requireNonNull(strategy); }

    void addRoom(Room room) {
        rooms.put(room.id(), room);
        bookingsByRoom.put(room.id(), new ArrayList<>());
    }

    /** Check and insert happen under the room's lock, so two callers cannot both win the same slot. */
    Booking book(String roomId, String userId, Slot slot) {
        List<Booking> list = bookingsByRoom.get(roomId);
        if (list == null) throw new NoSuchElementException("no room " + roomId);
        synchronized (list) {
            for (Booking b : list) {
                if (b.slot().overlaps(slot)) throw new BookingConflictException(roomId + " is taken at that time");
            }
            Booking booking = new Booking(nextId.getAndIncrement(), roomId, userId, slot);
            list.add(booking);
            bookingsById.put(booking.id(), booking);
            return booking;
        }
    }

    /** Find a free room for the group using the strategy, then book it (retrying if someone beats us). */
    Booking bookAny(String userId, int attendees, Slot slot) {
        for (int attempt = 0; attempt < 3; attempt++) {
            List<Room> free = new ArrayList<>();
            for (Room r : rooms.values()) {
                if (r.capacity() >= attendees && isFree(r.id(), slot)) free.add(r);
            }
            Room chosen = strategy.choose(free, attendees)
                    .orElseThrow(() -> new BookingConflictException("no room fits " + attendees + " people"));
            try {
                return book(chosen.id(), userId, slot);
            } catch (BookingConflictException raced) {
                // another thread took it between isFree() and book(); look again
            }
        }
        throw new BookingConflictException("rooms keep filling up, try again");
    }

    boolean isFree(String roomId, Slot slot) {
        List<Booking> list = bookingsByRoom.get(roomId);
        synchronized (list) {
            return list.stream().noneMatch(b -> b.slot().overlaps(slot));
        }
    }

    void cancel(long bookingId, String userId) {
        Booking b = bookingsById.get(bookingId);
        if (b == null) throw new NoSuchElementException("no booking " + bookingId);
        if (!b.userId().equals(userId)) throw new SecurityException("only the organiser can cancel");
        if (!bookingsById.remove(bookingId, b)) return;          // a concurrent cancel already did it
        List<Booking> list = bookingsByRoom.get(b.roomId());
        synchronized (list) { list.remove(b); }
    }

    List<Booking> bookingsFor(String roomId) {
        List<Booking> list = bookingsByRoom.get(roomId);
        synchronized (list) { return List.copyOf(list); }
    }
}

// ---------- driver ----------
public class RoomBooking {
    static LocalDateTime at(int hour, int minute) { return LocalDateTime.of(2026, 11, 18, hour, minute); }

    public static void main(String[] args) throws Exception {
        BookingService svc = new BookingService(new SmallestFitStrategy());
        svc.addRoom(new Room("Ada", 4));
        svc.addRoom(new Room("Turing", 10));

        Booking b1 = svc.book("Ada", "priya", new Slot(at(9, 0), at(10, 0)));
        System.out.println("booked " + b1);

        Booking b2 = svc.book("Ada", "arjun", new Slot(at(10, 0), at(11, 0)));   // touches, no overlap
        System.out.println("booked " + b2);

        try {
            svc.book("Ada", "sam", new Slot(at(9, 30), at(10, 30)));
        } catch (BookingConflictException e) {
            System.out.println("rejected: " + e.getMessage());
        }

        Booking b3 = svc.bookAny("sam", 3, new Slot(at(9, 30), at(10, 30)));   // Ada busy, so Turing
        System.out.println("bookAny chose " + b3.roomId());

        svc.cancel(b1.id(), "priya");
        System.out.println("Ada after cancel: " + svc.bookingsFor("Ada").size() + " booking(s)");

        // two threads race for the same slot: exactly one must win
        Slot contested = new Slot(at(14, 0), at(15, 0));
        int[] wins = {0};
        Runnable attempt = () -> {
            try { svc.book("Turing", Thread.currentThread().getName(), contested); synchronized (wins) { wins[0]++; } }
            catch (BookingConflictException ignored) { }
        };
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 8; i++) { Thread t = new Thread(attempt, "t" + i); threads.add(t); t.start(); }
        for (Thread t : threads) t.join();
        System.out.println("winners for 14:00 on Turing: " + wins[0]);
    }
}

Points worth saying out loud while you write it:

  • The overlap rule lives in one place (Slot.overlaps), and the half-open convention is a comment, not a guess.
  • Errors are exceptions with clear names (BookingConflictException), not null or false that callers forget to check.
  • The strategy picks; the service enforces. bookAny asks the strategy for a room, then books it through the same locked book method, and retries if another request took it in between.
  • The driver proves it: a normal booking, a touching booking that must succeed, an overlap that must fail, a cancel, and eight threads racing for one slot with exactly one winner.

Writing clean code under time pressure

  • No frameworks, no database. Use in-memory maps ("repositories") behind the service, and say a real system would put a database behind the same methods.
  • Names over comments. findFreeRoom needs no comment; process needs a paragraph.
  • Immutable where you can. Records in Java, frozen dataclasses in Python. Immutable objects can be shared between threads safely.
  • Validate at the edges. Constructors reject bad input (capacity 0, start after end), so the rest of the code can trust its data.
  • Skip the ceremony. You do not need getters and setters for every field, a Manager per class, or JavaDoc on every method. Spend the time on the hard rule.
  • Keep it compiling. Run the program every 10–15 minutes. A compile error found at minute 85 is a disaster; at minute 20 it is nothing.

Step 6: test it

In machine coding, the driver is your test suite; make it print results you can check at a glance. If time allows, add two or three real unit tests for the riskiest rule:

@Test
void touchingSlotsDoNotClash() {
    BookingService svc = new BookingService(new SmallestFitStrategy());
    svc.addRoom(new Room("Ada", 4));
    svc.book("Ada", "a", new Slot(at(9, 0), at(10, 0)));
    assertDoesNotThrow(() -> svc.book("Ada", "b", new Slot(at(10, 0), at(11, 0))));
    assertThrows(BookingConflictException.class,
                 () -> svc.book("Ada", "c", new Slot(at(9, 59), at(10, 30))));
}

The edge cases interviewers look for: boundaries (exactly touching slots, capacity exactly equal to the group), invalid input (end before start, unknown room), permission (cancelling someone else's booking), and the concurrent case.

Step 7 and beyond: concurrency

Almost every LLD problem has one shared, scarce thing: the last parking spot, the last seat, a room at 14:00, a user's balance. Find it, then say how you protect it.

Two requests, one slot: check-then-act and the fix

The bug pattern is always check-then-act: read a condition ("is it free?"), then act on it ("insert a booking") as two separate steps. Another thread can change the world in between. The fixes, from smallest to largest scope:

FixHowGood forCatch
Lock per resourcesynchronized (roomBookings) / one Lock per roomOne process, in-memory modelDifferent rooms don't block each other; must lock in a fixed order if you ever need two
One global locksynchronized on every service methodSimplest correct answerSerialises everything; fine for an interview, slow at scale
Atomic operationsConcurrentHashMap.putIfAbsent, AtomicInteger.compareAndSetSingle values (a seat id → holder)Doesn't cover multi-step rules like interval overlap
Database constraintUnique index, or SELECT … FOR UPDATE, or an exclusion constraint on time ranges (Postgres)Several app serversThe real answer once more than one process exists
Python threads and the GIL

CPython's global interpreter lock (GIL) lets only one thread run Python bytecode at a time, but it can switch threads between any two bytecodes, so check-then-act is just as broken in Python as in Java. x += 1 on a shared counter is several bytecodes and can lose updates. Use threading.Lock for multi-step rules. Python 3.13 also ships an optional free-threaded build without the GIL, which makes explicit locking even more important.

What interviewers grade

AreaStrong signalWeak signal
RequirementsAsks questions that change the design; states what is out of scopeStarts coding immediately, or asks 20 questions about the UI
ModellingFew classes with one clear job each; value objects; enums for fixed setsGod class; anaemic classes that are only getters
ExtensibilityInterfaces exactly where change is expected; can add a feature by adding a classPatterns everywhere, or none where they're obviously needed
Code qualityReadable names, small methods, validation, exceptions, immutabilityMagic numbers, copy-pasted blocks, null returns
CorrectnessDemo runs; edge cases handled; overlap and money rules rightDoesn't compile; happy path only
ConcurrencyNames the race and the narrowest correct lock"It's single-threaded" without being told so
CommunicationExplains trade-offs as they go; takes hints wellSilent for 40 minutes; defends a bad choice

Common mistakes

  • Designing the database instead of the objects. Tables come later, if at all. Start with behaviour.
  • Building everything at once. Get one flow working end to end, then widen.
  • Using inheritance for variation that is data. WeekendTicket extends Ticket when a pricing rule would do.
  • Floating-point money. 0.1 + 0.2 != 0.3. Use integer cents (long) or BigDecimal / Decimal.
  • Leaking internals. Returning your internal List lets callers modify it without the lock; return a copy or an unmodifiable view.
  • Ignoring time. Calling Instant.now() deep inside logic makes it untestable; pass in a Clock (Java) or a now function (Python) so tests can control time.

When not to follow the full method

  • A 20-minute question inside another round. Skip the diagram; state three requirements, write the core class, mention the race.
  • The interviewer leads. If they hand you requirements and a skeleton, don't re-clarify everything: confirm the two or three ambiguous points and start.
  • A pure algorithm hidden as LLD. "Design an LRU cache" is mostly about the data structure; the class design is small. Spend the time on getting O(1) right (see Design an LRU cache).

In the interview

Your turn: apply the method to a car rental system

"Design a car rental system." Spend five minutes: write 4–5 requirements with one out-of-scope item, list the classes with one responsibility each, name the one or two things that vary, and name the race.

Compare with our answer
ClassResponsibility
CarId, category (enum: ECONOMY, SUV…), branch, daily rate
BranchLocation and the cars stationed there
ReservationCustomer, car, date range (a half-open value object, like Slot), status
RentalServiceSearch available cars, reserve, pick up, return, cancel
PricingStrategyDaily, weekly discount, weekend rate

Requirements to agree: search by branch, category and dates; reserve a specific car; pick up and return (late return costs extra); cancel before pickup. Out of scope: payments, insurance, loyalty points.

A strong answer mentions: a date-range value object with one overlap rule · reservations checked and inserted under a lock per car (the race is two customers, one car, overlapping dates) · pricing as a strategy, chosen per branch or season · status as an enum (RESERVED → PICKED_UP → RETURNED / CANCELLED) with legal transitions checked · money in integer cents or a decimal type.

Your turn: spot the bug

A candidate's booking method passes their demo. Find at least four problems.

class BookingService {
    private final Map<String, List<Booking>> bookings = new HashMap<>();
    private long nextId = 1;

    Booking book(String roomId, String user, Slot slot) {
        List<Booking> list = bookings.get(roomId);
        for (Booking b : list)
            if (b.slot().start().equals(slot.start())) throw new BookingConflictException("taken");
        Booking bk = new Booking(nextId++, roomId, user, slot);
        list.add(bk);
        return bk;
    }
}
Compare with our answer
  1. Wrong overlap rule: only equal start times clash, so 9:00–10:00 and 9:30–10:30 both succeed. Use start < other.end && other.start < end.
  2. Check-then-act race: two threads both pass the loop and both append. Lock the room's list around check and insert.
  3. nextId++ / self.next_id += 1 is not atomic: two bookings can get the same id. Use AtomicLong or take the id under a lock.
  4. Unsafe collections: HashMap and ArrayList (or a list being appended while another thread iterates it) are not safe for concurrent use without a lock.
  5. Unknown room crashes with a NullPointerException / KeyError instead of a clear error.
Booking book(String roomId, String user, Slot slot) {
    List<Booking> list = bookings.get(roomId);                 // ConcurrentHashMap
    if (list == null) throw new NoSuchElementException("no room " + roomId);
    synchronized (list) {
        for (Booking b : list)
            if (b.slot().overlaps(slot)) throw new BookingConflictException(roomId + " is taken");
        Booking bk = new Booking(nextId.getAndIncrement(), roomId, user, slot);   // AtomicLong
        list.add(bk);
        return bk;
    }
}

A strong answer mentions: the interval overlap formula · check-then-act and a per-room lock · a non-atomic id counter · thread-unsafe collections · a clear error for an unknown room.

LLD interviews on one page
  • Two formats: OOD discussion (45–60 min, design + key methods) vs machine coding (60–120 min, code must run). Ask which.
  • Seven steps: clarify → entities → class design → core flows → code → test → extend. Say the time plan out loud.
  • Entities: nouns with data and behaviour → classes; describing nouns → fields; verbs → methods on the owner of the data.
  • Value objects (Slot, Money, DateRange) hold one rule each and remove bugs everywhere else.
  • Patterns only for a stated signal: varies → Strategy; notify → Observer; status rules → State; undo → Command. No Singleton by reflex.
  • Code order: models → interface for what varies → service → driver. Compile every 10–15 minutes; working beats complete.
  • Concurrency: find the scarce shared thing; check-then-act is the bug; lock per resource; database constraint across servers.
  • Money in integer cents or decimals; time injected through a clock so tests can control it.
Check what stuck

1. You have a 90-minute machine-coding round for "design Splitwise". At minute 60 you have clean classes for five features but nothing runs yet. What is the best move?

2. Requirements say: "Members borrow books; each book has a title and an ISBN; the shelf colour is printed on the label." Which modelling is best?

3. A candidate makes BookingService a Singleton "because the system only has one". What is the main objection?

4. Two requests call if (isFree(room, slot)) add(booking) at the same moment for the same room and time. What happens, and what is the fix?

5. Your in-memory booking service uses synchronized per room. The interviewer says it will run on three servers sharing one Postgres database. What should change?

6. Which situation is the strongest reason to introduce an interface in an LLD design?

7. A booking rule uses LocalDateTime.now() inside cancel() to check "no cancellations within 1 hour of the start". Why might an interviewer push back?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.