Design Pattern

LLD Interview Framework

Clean Java-only production-ready implementation.


What Problem It Solves

A machine coding round hands you a vague problem statement, one editor and roughly an hour. The usual failure is not a missing design pattern. It is starting to type classes after one minute of reading, discovering a missing requirement at minute thirty, and having no working output at minute sixty. This framework replaces that with a fixed order of work in which every step produces something small that can be checked before the next step starts.

Interviewers score five things, and the framework produces them in the same order. They look at whether you scoped the problem, whether the model matches the requirements, whether the public API is clean, whether the code runs and stays correct under concurrent callers, and whether the design survives one follow-up change. Each section below maps to one of those scores.

The Timed Plan for a 45 to 60 Minute Round

Seven slices cover the whole round. The table gives minutes for a 60 minute round and for a 45 minute round, plus what each slice must produce and why it sits where it does in the order.

Slice60 min45 minWhat you produceWhy this slice exists
1. Clarify54Five lines of agreed scope and a list of what is outA wrong assumption found now costs seconds, and the same assumption found at minute thirty costs the whole design
2. Entities and relationships54Nouns turned into classes, with a sketch of who owns whomCode written against a wrong model gets rewritten, so the model is checked while it is still a list of names
3. API and flow54Public method signatures and the main flow in wordsFixing the contract before the implementation means you never rewrite the callers
4. Code the core2520Entities, the orchestrator and the main flow, compiling and runningThe longest slice, spent on the happy path and the rules you named, writing the smallest class that makes the flow run
5. Concurrency pass54A named guard around every shared mutable structureIt comes after the core works so you guard real code instead of imagined code
6. Driver and edge cases54A main method that prints results for the happy path and three edge casesPrinted output the interviewer can see is worth more than any claim that it works
7. Extension105One follow-up change made as a small diff, then the driver run againThe last question is almost always a change request, and unspent time keeps the answer calm

If you fall behind, cut polish from the code slice and never cut the concurrency pass or the driver. A design that runs and is guarded beats a more complete design that was never executed. Say the time out loud at each slice boundary so the interviewer sees you managing the clock.

Clarifying Questions Checklist

Spend the first five minutes asking questions from this checklist, and write the answers as comments at the top of the file. Each question exists because its answer changes a concrete part of the design.

AreaQuestion to askWhat it changes in the design
ScopeWhich operations must work today, and which are explicitly out of scope?Decides the public API and the entity list, and gives you permission to ignore everything else
ScaleRoughly how many entities and how many requests should this handle?A few hundred entities in memory means plain maps and lists, so indexes and sharding can be skipped. Millions of entities changes the data structures.
ConcurrencyCan several callers use it at the same moment, and which operation must never be wrong when they do?Tells you whether the concurrency pass is required and which invariant it protects
PersistenceIs in-memory state enough, or must data survive a restart?In-memory means no storage layer. Saying you would add a repository interface later is enough.
What to skipMay I stub payments, authentication, notifications and any user interface?Buys back ten minutes. Get the yes out loud so skipping is a decision and not an omission.
Rules and tiesWhat should happen on a tie, a failure or a duplicate request?Surfaces the edge cases you will later prove in the driver

Finish by restating the scope in two sentences and naming any assumption the interviewer did not answer. A correction at this point costs one sentence, and it also shows that you treat requirements as something to pin down before building.

From Requirements to Entities and Relationships

Read the requirements once and underline every noun and every verb. Nouns are candidate entities and verbs are candidate methods, but most nouns should not become classes. The table shows how to sort what you underlined.

Signal in the requirementsBecomesParking Lot example
A noun with its own identity and changing stateAn entity classA Spot is free or taken and a Ticket is open or closed
A noun that is only a value of another nounA field and not a classThe license plate is a String on the ticket
A noun with a fixed set of kindsAn enum first, and a class hierarchy only if the kinds behave differentlySize with the values SMALL and LARGE
A verb that changes one entity's own dataA method on that entityA spot marks itself taken or free
A verb that spans several entitiesA method on the orchestratorpark finds a spot, creates a ticket and records it
A rule the interviewer hints may changeA policy object or function passed inThe fee rule

Ownership versus reference

For every pair of entities decide which of two relationships you mean, because the answer fixes who creates, stores and deletes each object. Ask whether the child still makes sense when the parent is gone.

RelationshipTest questionHow to model itParking Lot example
Composition (ownership)If the parent is deleted, does the child still make sense? No.The parent creates the child and holds the only reference to itA floor owns its spots, since a spot without a floor means nothing
Association (reference)Does the child have a life of its own outside this relationship? Yes.Hold an id or a reference and never create or delete the child from hereA ticket refers to a spot, and the spot outlives the ticket

Sketch the result as one line per relationship, for example that the lot owns its spots and a ticket refers to a spot, and show it to the interviewer before coding. The sketch also tells you where the concurrency guard will go later, because the owner of a piece of data is the natural place to protect it.

Choose Patterns Only When Forced

A pattern is a response to a symptom you can point at in code you have already written. Name the symptom out loud, then apply the smallest version of the pattern that removes it. A pattern added because it might be useful later adds classes the interviewer must read and you must finish in the remaining time.

Symptom in your codePatternThe smallest change
A growing if-else or switch on a type to choose a calculation, such as fees or allocationStrategyExtract an interface with one method and pass the implementation in. A plain function parameter is often enough at first.
An object that behaves differently by phase and carries several boolean flagsStateMove each phase's behavior into its own state class and let the owner delegate to the current one
Callers switch on a type string only to create the right objectFactoryOne method takes the kind and returns the object, so the switch lives in a single place
A constructor with many optional parameters, or half built invalid objectsBuilderCollect the fields step by step and validate once in build
Several components must react when one thing changesObserverThe subject keeps a list of listeners and notifies them, so it never names concrete receivers
Logging, caching or discounts must be layered on an object without a subclass for every combinationDecoratorWrap the object in a class with the same interface that adds exactly one behavior
A request must pass through ordered checks and any check may stop itChain of ResponsibilityGive every check the same interface and link them in order
Operations must be queued, undone or logged as dataCommandTurn each operation into an object with execute and, if needed, undo
Several algorithms share one skeleton and differ in a step or twoTemplate MethodPut the skeleton in a base class and leave the varying steps abstract
Leaves and groups must be treated the same, as with files and foldersCompositeOne interface for both, with groups holding a list of children
Callers are full of null checks for a missing collaboratorNull ObjectA do-nothing implementation of the same interface
Creating an object is expensive and instances can be reused, as with connections or workersObject PoolHand out and take back instances from a bounded pool
The problem statement demands exactly one shared instanceSingletonCreate it once in main and pass it in. Use a static accessor only if the requirement truly needs one.

Use the sentence form "I have this symptom, so I will extract this pattern." If you cannot finish the sentence with a symptom from your own code, leave the pattern out. One or two patterns that each remove a visible symptom read as judgment, while six patterns on a three class problem read as memorized.

API First Design and a Thin Orchestrator

Before writing any class body, write the public methods the outside world will call, with parameter and return types. For a parking lot that is two methods, park(plate, size) and leave(ticketId, minutes). Writing them first forces three decisions that are expensive to change later. You decide what identifies things at the boundary, which should be an id and not an object reference. You decide how expected failures are reported, which should be an empty result for a full lot and neither an exception nor a null. You decide what the caller gets back, which here is a ticket to present later and a fee at exit.

The orchestrator is the one class callers talk to. Keep it thin. It validates input, sequences the steps, takes the lock and delegates, while the rules live with the data that owns them or in an injected policy.

ConcernWhere it livesWhy
Input checks and step orderThe orchestratorIt is the only class that sees the whole flow
A rule about one entity's own dataThat entityThe rule stays next to the data it protects
A rule that varies or may changeAn injected policyChanging the rule never edits the orchestrator
Lookup maps and bookkeepingThe orchestrator, behind its guardOne owner keeps the concurrency guard simple
Printing and formattingThe driverCore classes stay quiet and easy to test

A quick smell test is whether the orchestrator has a method longer than about twenty lines or imports every other class. If it does, rules have leaked into it and it is turning into a god class.

The Concurrency Checklist

Run these four questions over every class once the core works. They turn the vague worry that the code might not be thread safe into a specific claim that you can state and then test.

QuestionWhat to answerParking Lot answer
What is shared?List each mutable structure that more than one caller can reachThe queues of free spots and the map of active tickets
What is the invariant?One sentence that must hold after every operationEvery spot is either free or held by exactly one active ticket
What is the guard?The single mechanism that protects the invariant, named, with the place where it is takenOne lock on the lot, held for the whole of park and of leave
Where is check-then-act?Every place the code reads a condition and then acts on it in a separate stepReading that a queue is not empty and then taking a spot from it

Check-then-act is where silent bugs live

Two callers can both read that one spot is free and then both take it. A guard that wraps only the read or only the write does nothing for this. The check and the act must sit inside the same critical section, or be replaced by one atomic call such as putIfAbsent, computeIfAbsent or compare and set.

Picking the primitive

Start with one lock around the orchestrator and say that finer locks come later if measurement shows contention. Reach for a dedicated primitive only when the situation matches one of these rows.

SituationPrimitivePattern page
Many independent tasks, and you want to bound how many run at onceA fixed pool of worker threadsThread Pool
Producers and consumers run at different speeds, or work must be handed from one thread to anotherA bounded queue that blocks when full or emptyBlocking Queue
Reads vastly outnumber writes on one shared structureA lock with a shared read mode and an exclusive write modeRead-Write Lock
Code takes more than one lock and different paths take them in different ordersOne global lock order, or try-lock with back-offDeadlock Prevention

Finish by saying plainly what the guard does not cover. A lock protects one process only. Across several servers the same invariant needs a database transaction, a version check, a distributed lock or an idempotency key, and Idempotency and Exactly-Once Effects explains the last of those.

Write a Driver That Proves It Works

A driver is a main method that runs a scripted scenario against the public API and prints what happened. It is not a test framework, and it needs no assertion library. Its job is to turn the claim that the design should work into output the interviewer can read. Write it as soon as the core compiles, and run it before you describe the result.

Cover the happy path first, then these three edge cases. Together they exercise the boundary, the bookkeeping and the guard.

Edge caseWhat to doWhat it proves
1. Capacity exhaustedAsk for one more resource than existsThe failure is a clear result that does not throw, and the state is unchanged, so later calls still work
2. Repeated or invalid operationRelease the same thing twice, then allocate everything and countThe second release is rejected and no duplicate free slot appeared, which the count confirms
3. Concurrent race for the last resourceRelease many threads at the same instant, all asking for a few resourcesExactly as many calls succeed as there are resources, and each winner got a different one

A single threaded run can never reveal a missing guard, which is why the third case uses real threads released together. If time allows, comment the guard out once and run the driver again. Watching the winner count exceed the capacity proves that the test can fail, and that makes the passing run mean something.

Handling the Extension Request

The last question is almost always a change request, such as pricing by vehicle size or a new kind of spot. The interviewer is checking whether your design absorbs the change in one place. A design is easy to extend when each likely change has a seam, which is a single point where new behavior plugs in without editing the code around it.

Show the extension in three moves. First name the seam before touching code. Then make the smallest diff that uses it. Finally run the same driver again and point out that the earlier output is unchanged.

Extension requestSeam that absorbs itWhere the diff lands
Charge by the minute and by sizeThe injected fee policyOne new function passed to the constructor, with ParkingLot unchanged
Add a new spot kind such as electricA free list per kind, built from whatever kinds the spots declareA new value in the size type and the new spots in the setup, with ParkingLot unchanged
Accept card, cash or UPIA payment interface behind a factoryA new class and one line in the factory. This is the moment Factory becomes forced.
Support several floorsOwnership, since a floor can own its spotsA Floor class holding spots, with the lot iterating over floors. This is an entity change and you should say so.
Reserve a spot in advanceNone in the first designA new Reservation entity and a new rule inside park. Say plainly that this is a model change and not a plug-in.

Being honest about the last two rows scores better than pretending everything is a plug-in. An interviewer who sees you identify that a request needs a model change, and then make it cleanly, learns more about your design skill than from a request that happened to fit.

Worked Example: Parking Lot Through Every Step

This walkthrough applies each step to the Parking Lot problem. The full design with floors, pricing, payments and a class diagram is in the Parking Lot article, and the skeleton at the bottom of this page is a deliberately small runnable version of the same idea.

StepParking Lot decision
1. ClarifyAsk about vehicle kinds, floors, payment, gates and concurrent entry. Agreed scope is park and leave with a ticket, two sizes that must match exactly, a fee from a rule, in-memory state and several gates calling at once. Payments and floors are out.
2. Entities and relationshipsThe nouns are lot, floor, spot, vehicle, ticket, gate, fee and plate. Keep Spot, Ticket and the orchestrator ParkingLot. The plate is a field, floor and gate are out of scope and the fee is a policy. The lot owns its spots and a ticket refers to a spot.
3. API and flowpark(plate, size) returns a ticket or nothing and leave(ticketId, minutes) returns the fee or nothing. Parking takes a free spot of that size, creates a ticket and records it. Leaving removes the ticket, frees its spot and computes the fee.
4. Patterns only when forcedNone by name in the first pass. The fee is passed in as a function, which is the lightest form of Strategy. The full article adds Strategy classes for pricing and a Factory for payments once those rules exist.
5. Code the coreWrite Spot, Ticket and ParkingLot with its two methods and nothing else. Printing stays in the driver.
6. Concurrency passShared state is the free queues and the active ticket map. The invariant is that each spot is free or held by one active ticket. The guard is one lock inside park and leave, and the check-then-act is the empty check followed by the removal. In the full Java article parkVehicle and checkoutVehicle are likewise synchronized.
7. Driver and edge casesA second large vehicle when the only large spot is taken, a repeated exit on one ticket, and twenty threads racing for two small spots.
8. ExtensionThe interviewer asks for per-minute pricing that depends on size. Pass a different fee function, leave ParkingLot alone and run the driver to show a small stay of 90 minutes pays 90 and a large stay of 10 minutes pays 30.

Where It Shows Up

These problems reward different steps of the framework most. Practice each one with the clock running and check yourself against the step named in the second column.

ProblemStep it stressesWhy
Parking LotEntities, ownership and the allocation guardFloors own spots, tickets refer to them, and allocation must be a single guarded step
Vending MachineChoosing a pattern only when forcedBehavior depends on the machine phase, so boolean flags are the symptom that forces State
Elevator SystemPatterns and concurrency togetherA dispatch strategy picks the elevator and each elevator synchronizes its own state
Meeting SchedulerThe concurrency checklistDouble booking is a check-then-act race, and each room holds its own lock so rooms book in parallel
API Rate LimiterThe extension requestSeveral algorithms sit behind one interface and are configured per client, so a new algorithm is a plug-in
Tic-Tac-ToeEntities and extensible rulesA small model where win rules are strategies you can add without editing the game class
In-Memory Key-Value StoreAPI first designThe public surface of get, set, delete and transactions is settled before any internals

Common Interview Traps

TrapWhyFix
Over-engineering with patternsExtra classes eat the clock and hide the main flow, and the interviewer cannot tell which ones you neededName the symptom first, apply the smallest pattern, and start with a function parameter
A god class that validates, allocates, prices and printsIt cannot be extended without editing it, and every follow-up request lands in the same fileKeep the orchestrator to sequencing and push rules to entities and injected policies
Skipping the driverNothing proves the code works, and the bugs surface while the interviewer is watchingWrite the driver as soon as the core compiles and print results for three edge cases
Silent concurrency bugsCheck-then-act races give wrong answers only under load and never throw an exceptionRun the four question checklist, name the guard, and prove it with threads released together
Coding before clarifyingA wrong assumption invalidates code you have already writtenSpend five minutes on the checklist and write the agreed scope at the top of the file
A class for every nounPlain values get promoted to classes and the model becomes heavyPromote a noun only when it has an identity and state that changes
Throwing or returning null for expected failuresCallers forget the null check or are surprised by an exception on a normal case such as a full lotReturn an optional or a result for expected failures and keep exceptions for programming errors
Working in silenceThe interviewer cannot give hints or credit reasoning they never hearNarrate each decision and each time check in one sentence

A Runnable Skeleton That Follows the Framework

Each tab is the same small Parking Lot built in framework order. It has two entities, one thin orchestrator with a single guard, a fee rule passed in as a function, and a driver that covers the happy path, the three edge cases and the pricing extension. Read the driver first, because it states what the design promises.

The guard differs by language for a reason. Java uses synchronized and Python uses a Lock. TypeScript relies on its single threaded event loop, which is enough here because no await sits between the check and the act, and so the third edge case runs as concurrent tasks instead of threads. In Java and Python the fee function is called after the lock is released, so a policy that calls back into the lot cannot deadlock it.

import java.util.*;
import java.util.concurrent.*;

// Scope: park and leave, exact size match, fee from a rule, in memory, many gates at once.
enum Size { SMALL, LARGE }

record Spot(String id, Size size) {}
record Ticket(String id, String plate, Spot spot) {}

// The one seam we expect to change: how a stay is priced.
interface FeePolicy { long fee(Size size, int minutes); }

// Thin orchestrator. Invariant: every spot is either free or held by exactly one active ticket.
class ParkingLot {
    private final Map<Size, Deque<Spot>> free = new EnumMap<>(Size.class);
    private final Map<String, Ticket> active = new HashMap<>();
    private final FeePolicy fees;
    private int nextTicket = 1;

    ParkingLot(List<Spot> spots, FeePolicy fees) {
        this.fees = fees;
        for (Size size : Size.values()) free.put(size, new ArrayDeque<>());
        for (Spot spot : spots) free.get(spot.size()).addLast(spot);
    }

    // Guard: the lot's monitor. The emptiness check and the removal share one critical section.
    synchronized Optional<Ticket> park(String plate, Size size) {
        Deque<Spot> queue = free.get(size);
        if (queue.isEmpty()) return Optional.empty();
        Ticket ticket = new Ticket("T" + nextTicket++, plate, queue.removeFirst());
        active.put(ticket.id(), ticket);
        return Optional.of(ticket);
    }

    // Removing the ticket is the check and the act in one step, so a repeated exit finds nothing.
    OptionalLong leave(String ticketId, int minutes) {
        Ticket ticket;
        synchronized (this) {
            ticket = active.remove(ticketId);
            if (ticket == null) return OptionalLong.empty();
            free.get(ticket.spot().size()).addLast(ticket.spot());
        }
        return OptionalLong.of(fees.fee(ticket.spot().size(), minutes));
    }
}

public class Main {
    static List<Spot> spots() {
        return List.of(new Spot("S1", Size.SMALL), new Spot("S2", Size.SMALL), new Spot("L1", Size.LARGE));
    }

    public static void main(String[] args) throws Exception {
        FeePolicy flat = (size, minutes) -> 10;
        ParkingLot lot = new ParkingLot(spots(), flat);

        Ticket first = lot.park("KA-01", Size.SMALL).orElseThrow();
        System.out.println("happy path: " + first.plate() + " parked at " + first.spot().id() + " with ticket " + first.id());
        System.out.println("happy path: exit after 90 minutes pays " + lot.leave(first.id(), 90).getAsLong());

        // Edge 1: the only large spot is taken, so the next large vehicle is refused without an exception.
        lot.park("KA-02", Size.LARGE).orElseThrow();
        System.out.println("edge 1: second large vehicle rejected: " + lot.park("KA-03", Size.LARGE).isEmpty());

        // Edge 2: exit twice with one ticket, then fill every small spot and look for a duplicate.
        Ticket again = lot.park("KA-04", Size.SMALL).orElseThrow();
        lot.leave(again.id(), 5);
        System.out.println("edge 2: repeated exit rejected: " + lot.leave(again.id(), 5).isEmpty());
        List<String> handedOut = new ArrayList<>();
        for (int i = 0; i < 3; i++) lot.park("KB-" + i, Size.SMALL).ifPresent(t -> handedOut.add(t.spot().id()));
        System.out.println("edge 2: three small vehicles tried, spots handed out: " + handedOut);

        // Edge 3: twenty threads start together and fight for two small spots.
        ParkingLot raced = new ParkingLot(spots(), flat);
        ExecutorService pool = Executors.newFixedThreadPool(20);
        CountDownLatch go = new CountDownLatch(1);
        List<Future<Optional<Ticket>>> attempts = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            String plate = "R-" + i;
            attempts.add(pool.submit(() -> { go.await(); return raced.park(plate, Size.SMALL); }));
        }
        go.countDown();
        Set<String> won = new TreeSet<>();
        int winners = 0;
        for (Future<Optional<Ticket>> attempt : attempts) {
            Optional<Ticket> ticket = attempt.get();
            if (ticket.isPresent()) { winners++; won.add(ticket.get().spot().id()); }
        }
        pool.shutdown();
        System.out.println("edge 3: 20 threads raced for 2 small spots, winners " + winners + ", distinct spots " + won);

        // Extension: only the function passed in changes, the ParkingLot class is untouched.
        ParkingLot metered = new ParkingLot(spots(), (size, minutes) -> (size == Size.SMALL ? 1L : 3L) * minutes);
        Ticket small = metered.park("M-1", Size.SMALL).orElseThrow();
        Ticket large = metered.park("M-2", Size.LARGE).orElseThrow();
        System.out.println("extension: small 90 minutes pays " + metered.leave(small.id(), 90).getAsLong()
            + ", large 10 minutes pays " + metered.leave(large.id(), 10).getAsLong());
    }
}

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