CSCheatsheets
Object design

Low-Level Design

OOP and SOLID, all 23 design patterns, 23 classic problems with entities and APIs, 3 full worked designs, concurrency and the machine-coding round.

11sections
55cards
10diagrams
0%known

00LLD atlas: topics and routes

The whole sheet on one screen. Select an area or topic to jump to it; hover the boxes in any diagram below for explanations.

How to use this sheet#

  1. Learning: OOP foundations, then the pattern catalogue; learn when each pattern applies, not just what it is.
  2. Practising: take a problem from the playbook, set a 90-minute timer, and build a runnable solution with a demo driver.
  3. Before a machine-coding round: re-read the time plan, package layout and rubric, then one worked design.
  4. Interview tomorrow: pattern trigger phrases, the problem playbook table, concurrency hazards, then the last-minute checklist.

What interviewers score#

SignalWhere it's covered
Clear entities and ownershipResponsibility guide · GRASP
Extensible without editsSOLID · Pattern triggers
Working code earlyTime plan · Package layout
Thread-safety statedHazards · Primitives
Edge cases and testsErrors · Testing
Check yourself 2 questions
  1. Which principle signals 'extensible without edits'?

    Show answer

    Open/closed, usually via Strategy or Factory.

  2. Why produce working code early?

    Show answer

    Interviewers score a running core over a perfect but unfinished design.

Takeaway Clear entities and ownership, extensibility without edits, working code early, and handling of concurrency and errors.

01LLD: model behavior, state, and boundaries

60-minute interview route#

TimeFocus
0–6Use cases, constraints, edge cases
6–12Entities, value objects, invariants
12–18Public method signatures and ownership
18–24Relationships and state transitions
24–44Implement core path; extend only as needed
44–50Concurrency and atomicity
50–60Errors, races, tests, extension points

What interviewers score

  • Entities with one job each, and invariants enforced inside them rather than by callers.
  • Patterns used for a real variation point, and named only after the code needs them.
  • A working core path early, then extensions.
  • Thread safety reasoned out loud: what is shared, and what guards it.
  • Testability: injected clock and ID generator, small interfaces, edge cases named.
  • Readable names, small methods, and no dead abstractions.
Check yourself 2 questions
  1. What comes right after use cases?

    Show answer

    Entities, value objects and invariants.

  2. When do you write method signatures?

    Show answer

    Before relationships and code, around minutes 12–18.

Takeaway Use cases, entities and invariants, method signatures, relationships and states, code the core, then concurrency and extensions.

Object design flow#

flowchart TD
 U[Use cases + edge cases] --> I[Invariants and state ownership]
 I --> M[Entities + immutable values]
 M --> A[Small public interfaces]
 A --> S[Services orchestrate behavior]
 S --> P[Pattern for real variation]
 P --> C[Concurrency / transaction boundaries]
 C --> T[Test transitions, races, failures]
Check yourself 2 questions
  1. Where should invariant-preserving operations live?

    Show answer

    Near the state they protect, on the entity.

  2. What do services do?

    Show answer

    Orchestrate behaviour across entities.

Takeaway Use cases → invariants and state ownership → entities and values → small interfaces → orchestrating services.

Responsibility guide#

Building blockOwnsDesign cue
EntityIdentity and lifecycle stateKeep invariant-preserving operations near state.
Value objectImmutable values such as Money or AddressValidate once; compare by value.
ServiceUse-case orchestrationCoordinate collaborators; avoid god classes.
Repository / gatewayPersistence or external boundaryDepend on an interface for testability.
Strategy / stateReplaceable rule or legal transitionsUse when the variation is visible.
Check yourself 2 questions
  1. Give an example of a value object.

    Show answer

    Money or Address.

  2. What does a repository hide?

    Show answer

    Storage details behind a collection-like interface.

Takeaway Entities own identity and lifecycle, value objects are immutable, services orchestrate, repositories hide storage.

02Object-oriented foundations

The vocabulary interviewers expect you to use while modeling. Name the principle when you apply it.

Four pillars of OOP#

PillarWhat it meansInterview cue
EncapsulationState is private; change it only through methods that keep invariantsNo public setters on balance; expose deposit() / withdraw()
AbstractionCallers depend on what an object does, not howPaymentGateway interface hides Stripe/Razorpay details
Inheritance"is-a" reuse of type and behaviourUse for true subtypes only; prefer composition for reuse
PolymorphismOne call, many implementations (runtime dispatch / overloading)Replace if type == … chains with subclasses or strategies
Check yourself 2 questions
  1. Encapsulation interview cue?

    Show answer

    No public setter on balance; expose deposit() and withdraw().

  2. What does polymorphism let you do?

    Show answer

    Call the same interface with different behaviours.

Takeaway Encapsulation, abstraction, inheritance and polymorphism; protect invariants with methods, not public setters.

UML class relationships#

RelationNotationLifetimeCode shape
Dependencydashed arrowtemporary useparameter or local variable
Associationsolid lineindependentfield holding a reference
Aggregationhollow diamondpart outlives wholeTeam has Players passed in
Compositionfilled diamondpart dies with wholeOrder creates its OrderLines
Inheritancehollow triangle, solid—class Car extends Vehicle
Realizationhollow triangle, dashed—class Card implements Payment
Multiplicity: write 1, 0..1, 1..*, * on both ends. It drives collection types and null checks.
Check yourself 2 questions
  1. Composition versus aggregation?

    Show answer

    In composition the part's lifetime is owned by the whole; in aggregation it's independent.

  2. Code shape of a dependency?

    Show answer

    A parameter or local variable.

Takeaway Dependency, association, aggregation, composition, inheritance and realisation differ in lifetime and code shape.

SOLID with the smell and the fix#

PrincipleRuleSmell you'll seeFixLLD example
S · Single responsibilityOne reason to changeInvoice computes, prints and saves itselfSplit into calculator, printer, repositoryParkingLot doesn't compute fees; FeeCalculator does
O · Open/closedExtend without editingGrowing switch(paymentType)Interface + new class per variantAdd UpiPayment without touching checkout
L · Liskov substitutionSubtypes honour the parent's contractSquare extends Rectangle breaks setWidth; Penguin.fly() throwsRe-model the hierarchy; split capabilitiesFlyable as a separate interface
I · Interface segregationSmall, client-specific interfacesClasses implementing methods with throw UnsupportedOperationSplit fat interface into rolesPrinter, Scanner, Fax instead of Machine
D · Dependency inversionDepend on abstractions; inject themnew MySqlRepo() inside a serviceConstructor injection of an interfaceSwap in-memory repo for tests
Check yourself 2 questions
  1. SRP smell?

    Show answer

    One class that computes, prints and saves (several reasons to change).

  2. DIP fix?

    Show answer

    Depend on abstractions; inject implementations.

Takeaway Each SOLID principle has a recognisable smell and a standard fix.

Design principles beyond SOLID#

  • Composition over inheritance: assemble behaviour from parts; avoids fragile base classes.
  • Tell, don't ask: account.withdraw(x) rather than reading balance and deciding outside.
  • Law of Demeter: talk to direct collaborators only; avoid a.getB().getC().do().
  • DRY · KISS · YAGNI: no duplicated knowledge, simplest design that works, no speculative features.
  • High cohesion, low coupling: related behaviour together; few, narrow dependencies.
  • Program to interfaces; keep the domain free of framework and I/O code.
  • Immutability for value objects and anything shared across threads.
  • Fail fast: validate at construction; make illegal states unrepresentable (enums, types).
Check yourself 2 questions
  1. Tell, don't ask example?

    Show answer

    account.withdraw(x) rather than reading the balance and deciding outside.

  2. Why prefer composition?

    Show answer

    It avoids fragile base classes and allows swapping parts.

Takeaway Composition over inheritance, tell don't ask, Law of Demeter, DRY, KISS and YAGNI.

GRASP: who should own this responsibility?#

PrincipleAssign the responsibility to…
Information expertthe class that has the data needed
Creatorthe class that contains or aggregates the created object
Controllera use-case/facade object, not the UI
Polymorphismthe types that vary, not a conditional
Pure fabricationa made-up service class when no domain object fits (repository, notifier)
Indirectionan intermediary that decouples two classes
Protected variationsan interface wrapped around whatever is likely to change
Check yourself 2 questions
  1. Information expert rule?

    Show answer

    Give the responsibility to the class with the needed data.

  2. Creator rule?

    Show answer

    The class that contains or aggregates an object creates it.

Takeaway Information expert, creator, controller, low coupling, high cohesion and more decide ownership.

Language essentials for LLD: Java and Python#

TopicJavaPythonInterview cue
Interface vs abstract classInterface: a contract, multiple inheritance, default methods. Abstract class: shared state and code, single inheritanceabc.ABC with @abstractmethod; typing.Protocol for structural typingInterface for a capability or strategy; abstract class when subclasses share real state
Immutabilityfinal fields, no setters, defensive copies; record for value objects@dataclass(frozen=True), tuplesValue objects (Money, Address) and anything shared across threads
Equality and hashingOverride equals and hashCode together; equal objects must have equal hashes__eq__ and __hash__; frozen dataclasses generate bothMutating a field used in the hash after inserting into a HashMap/set loses the entry
EnumsEnums can hold fields and per-constant behaviourenum.Enum; add methods on the classModel statuses and types as enums, not strings
GenericsBounded types; PECS rule: producer extends, consumer superTypeVar, Generic[T] (hints only)Repository<T, ID>, Cache<K, V>
ExceptionsChecked (recoverable, declared) vs unchecked (programming errors); custom domain exceptionsAll unchecked; subclass Exception per domain errorSeatUnavailableException beats returning null or -1
Visibility and encapsulationprivate by default; package-private for testsLeading underscore by convention; @property for computed or read-only attributesNo public mutable fields on entities
Composition helpersConstructor injection; Optional for absent valuesPass collaborators to __init__; None checks or Optional[T]Makes swapping and testing collaborators trivial
Check yourself 2 questions
  1. Interface versus abstract class in Java?

    Show answer

    Interfaces are contracts with multiple inheritance; abstract classes share state and code with single inheritance.

  2. Python's equivalent of an abstract class?

    Show answer

    abc.ABC with @abstractmethod.

Takeaway Interfaces versus abstract classes, generics, enums, records and dataclasses, and equality and hashing.

03Design patterns catalogue

All 23 Gang of Four patterns plus the modern ones that show up in machine-coding rounds. In an interview, use one or two that the requirements actually call for, and say why.

Creational (5)#

PatternIntentUse when
SingletonOne shared instanceConfig, registry, ID generator; make it thread-safe and injectable
Factory MethodSubclass decides which product to createCreate Vehicle by type; hide new
Abstract FactoryFamilies of related productsUI themes, DB driver families (connection + command)
BuilderStep-by-step constructionMany optional params; immutable result (Pizza, HTTP request)
PrototypeClone an existing objectExpensive setup; templates (documents, game units)
Check yourself 2 questions
  1. When use Builder?

    Show answer

    For objects with many optional parameters.

  2. What should a Singleton be, in modern practice?

    Show answer

    Thread-safe and injectable.

Takeaway Singleton, Factory Method, Abstract Factory, Builder and Prototype manage object creation.

Structural (7)#

PatternIntentUse when
AdapterConvert one interface to anotherWrap a third-party payment SDK
BridgeSplit abstraction from implementationShape × renderer, Remote × device
CompositeTree of parts treated uniformlyFile system, nested comments, menu
DecoratorAdd behaviour by wrappingPizza toppings, stream compression, logging
FacadeSimple front for a subsystemBookingService over seats, payments, notifications
FlyweightShare intrinsic stateChess piece types, text glyphs, map tiles
ProxyStand-in that controls accessLazy loading, caching, auth, remote stub
Check yourself 2 questions
  1. Wrap a third-party payment SDK?

    Show answer

    Adapter.

  2. Tree of items treated uniformly?

    Show answer

    Composite.

Takeaway Adapter, Bridge, Composite, Decorator, Facade, Flyweight and Proxy shape how objects compose.

Behavioral (11)#

PatternIntentUse when
StrategySwap algorithmsPricing, matching, split types, eviction
StateBehaviour changes with stateVending machine, ATM, order lifecycle
ObserverNotify subscribers of changeStock alerts, order status, UI events
CommandRequest as an objectUndo/redo, job queues, macro recording
Chain of ResponsibilityPass along handlersLog levels, approval flows, middleware, ATM notes
Template MethodFixed skeleton, overridable stepsGame turn, report generation, data import
IteratorTraverse without exposing internalsCustom collections, paginated results
MediatorCentral hub for interactionsChat room, air-traffic control, UI dialogs
MementoSnapshot and restore stateEditor undo, game save points
VisitorNew operations over a fixed structureAST evaluation, tax/export over shapes
InterpreterGrammar evaluationRule engines, simple expression parsers
Check yourself 2 questions
  1. Vending machine behaviour changes with state?

    Show answer

    State pattern.

  2. Swap pricing algorithms?

    Show answer

    Strategy.

Takeaway Strategy, State, Observer, Command, Chain of Responsibility, Template Method and others organise behaviour.

Modern and enterprise patterns#

PatternUse when
Dependency injectionAlways: pass collaborators in; enables tests and swaps
RepositoryHide storage behind a collection-like interface
Unit of WorkCommit several changes atomically
SpecificationComposable business rules (eligibility, filters)
Null ObjectAvoid null checks (NoDiscount)
Object PoolReuse expensive objects (connections, threads)
Producer–ConsumerDecouple work creation from execution
Event bus / Pub-SubMany-to-many async notifications
Circuit breakerStop calling a failing dependency
Rule engineCoupons, fraud rules, pricing stored as data
Check yourself 2 questions
  1. When use dependency injection?

    Show answer

    Always: pass collaborators in for testability and swaps.

  2. Unit of Work?

    Show answer

    Commits several changes as one transaction.

Takeaway Dependency injection, repository, unit of work, CQRS, event sourcing and outbox appear in modern systems.

Patterns people confuse#

PairDifference
Strategy vs StateClient picks the strategy; a state object switches itself to the next state
Decorator vs ProxyDecorator adds behaviour and stacks; proxy controls access to the same interface
Adapter vs FacadeAdapter converts one interface; facade simplifies many
Factory Method vs Abstract FactoryOne product via inheritance vs a family via composition
Builder vs FactoryBuilder assembles step by step; factory picks a type in one call
Observer vs Pub-SubObserver: subject knows observers. Pub-sub: broker in between, often async
Template vs StrategyInheritance fills steps vs composition swaps the whole algorithm
Composite vs DecoratorBoth wrap the same interface; composite has many children, decorator one
Mediator vs ObserverMediator coordinates two-way logic; observer only broadcasts
Bridge vs AdapterBridge is designed up front so abstraction and implementation vary independently; adapter retrofits a mismatch
Command vs StrategyCommand is a request object you can queue, log or undo; strategy is an interchangeable algorithm
Flyweight vs SingletonFlyweight shares many immutable instances by key; singleton has exactly one instance
Chain of Responsibility vs DecoratorA chain link may stop the request; a decorator always delegates and adds behaviour
Check yourself 2 questions
  1. Strategy versus State?

    Show answer

    The client picks a strategy; a state object switches itself to the next state.

  2. Decorator versus Proxy?

    Show answer

    Decorator adds behaviour and stacks; Proxy controls access.

Takeaway Strategy vs State, Decorator vs Proxy, Adapter vs Facade and Factory vs Builder differ in intent.

Trigger phrase → pattern#

Requirement says…Reach for
"support multiple … types, add more later"Strategy + Factory
"behaves differently when idle / running / out of stock"State
"notify users when…"Observer
"undo", "replay", "queue requests"Command (+ Memento)
"escalate", "levels", "fall through"Chain of Responsibility
"folders contain files and folders"Composite
"add-ons", "toppings", "wrap with logging"Decorator
"integrate legacy / external API"Adapter
"exactly one …"Singleton, but prefer DI
"object with many optional fields"Builder
Check yourself 2 questions
  1. 'Support multiple types, add more later'?

    Show answer

    Strategy + Factory.

  2. 'Notify users when…'?

    Show answer

    Observer.

Takeaway Requirement phrases map to patterns: multiple types → Strategy + Factory, state-dependent behaviour → State, notify → Observer.

Which pattern? A quick picker#

What varies in the requirements?
1An algorithm or rule?
yes
Strategy
no
2Behaviour depends on state?
yes
State
no
3Others react to changes?
yes
Observer
no
4Create objects by type?
yes
Factory
no
5Add features by wrapping?
yes
Decorator
no
6Undo or queue requests?
yes
Command
no
Plain classes, no pattern
Check yourself 2 questions
  1. Behaviour depends on state?

    Show answer

    State.

  2. Create objects by type?

    Show answer

    Factory.

Takeaway Varying algorithm → Strategy; state-dependent → State; reactions → Observer; creation by type → Factory.

Vending machine state diagram#

stateDiagram-v2
  direction LR
  [*] --> Idle
  Idle --> HasMoney: insertCoin
  HasMoney --> HasMoney: insertCoin
  HasMoney --> Dispensing: select, stock and funds ok
  HasMoney --> Idle: refund
  Dispensing --> Idle: dispense and return change
Check yourself 2 questions
  1. What moves HasMoney to Dispensing?

    Show answer

    A selection with stock and enough funds.

  2. How do you return from HasMoney to Idle?

    Show answer

    Refund.

Takeaway Idle → HasMoney on coins → Dispensing on a valid selection → Idle; refunds return to Idle.

Code smells and the refactoring that fixes them#

SmellLooks likeRefactoring
God classOne class with dozens of methods and fields across concernsExtract class by responsibility; introduce a facade that delegates
Long methodA method that needs comments to explain its sectionsExtract method per step; name the steps
Switch on typeif type == CAR … elif type == BIKE … repeated in several placesReplace conditional with polymorphism (Strategy or subclasses)
Primitive obsessionMoney as double, IDs as raw strings, status as intIntroduce value objects and enums
Feature envyA method mostly reads another object's dataMove the method to the class that owns the data
Data clumps / long parameter listsThe same 4–5 arguments passed together everywhereIntroduce a parameter object or builder
Shotgun surgeryOne change requires edits in many classesMove related behaviour together; one place per decision
Anemic domain modelEntities are bags of getters/setters; all logic in servicesMove invariant-protecting behaviour into the entity
Hidden dependenciesnew or singletons called deep inside methodsConstructor injection behind interfaces
Speculative generalityAbstract layers and patterns with a single implementationInline them until a second variation appears (YAGNI)
Check yourself 2 questions
  1. Fix for a god class?

    Show answer

    Extract classes by responsibility, with a facade delegating.

  2. Fix for switch-on-type?

    Show answer

    Replace conditional with polymorphism (Strategy or State).

Takeaway God classes, long methods, switch-on-type and feature envy each have a standard refactoring.

Strategy + Factory (Java)#

interface PricingStrategy { Money price(Ride r); }
class StandardPricing implements PricingStrategy { public Money price(Ride r){ return r.km().times(12); } }
class SurgePricing    implements PricingStrategy {
    private final double mult; SurgePricing(double m){ mult = m; }
    public Money price(Ride r){ return r.km().times(12 * mult); }
}
final class PricingFactory {
    static PricingStrategy forDemand(double ratio){
        return ratio > 1.5 ? new SurgePricing(ratio) : new StandardPricing();
    }
}
// RideService depends on PricingStrategy only (DIP); new rule = new class (OCP)
Check yourself 2 questions
  1. What does the factory return?

    Show answer

    The right PricingStrategy implementation for the context.

  2. Adding a new pricing rule needs what?

    Show answer

    A new class, without editing existing ones.

Takeaway An interface per algorithm, implementations per type, and a factory choosing one.

State machine (vending machine)#

interface State {
    default void insertCoin(Machine m, int c){ throw new IllegalStateException(); }
    default void select(Machine m, String code){ throw new IllegalStateException(); }
    default void dispense(Machine m){ throw new IllegalStateException(); }
}
class Idle implements State {
    public void insertCoin(Machine m, int c){ m.addBalance(c); m.setState(new HasMoney()); }
}
class HasMoney implements State {
    public void insertCoin(Machine m, int c){ m.addBalance(c); }
    public void select(Machine m, String code){
        if (!m.inventory().available(code)) throw new OutOfStock(code);
        if (m.balance() < m.price(code)) throw new InsufficientFunds();
        m.setSelection(code); m.setState(new Dispensing());
    }
}
class Dispensing implements State {
    public void dispense(Machine m){ m.release(); m.returnChange(); m.setState(new Idle()); }
}
// Illegal transitions fail loudly; no if/else on a status enum
Check yourself 2 questions
  1. What do default methods do in the State interface?

    Show answer

    Throw IllegalStateException for invalid actions.

  2. Who switches the current state?

    Show answer

    The state objects, via the machine.

Takeaway Each state implements only valid actions; defaults throw for invalid ones.

Observer#

interface Subscriber { void onEvent(OrderEvent e); }
class OrderPublisher {
    private final List<Subscriber> subs = new CopyOnWriteArrayList<>();
    void subscribe(Subscriber s){ subs.add(s); }
    void publish(OrderEvent e){ for (Subscriber s : subs) s.onEvent(e); }
}
// CopyOnWriteArrayList: safe iteration while others subscribe.
// Async delivery? hand events to an ExecutorService or a BlockingQueue.
Check yourself 2 questions
  1. Why CopyOnWriteArrayList for subscribers?

    Show answer

    Safe iteration while subscribers are added or removed.

  2. What does a subscriber implement?

    Show answer

    An onEvent method.

Takeaway Publishers hold a thread-safe list of subscribers and notify each on events.

Thread-safe Singleton#

// 1) Holder idiom: lazy, thread-safe, no locks
final class IdGenerator {
    private IdGenerator() {}
    private static class Holder { static final IdGenerator I = new IdGenerator(); }
    static IdGenerator get(){ return Holder.I; }
}
// 2) Enum singleton: also safe against reflection/serialization
enum Registry { INSTANCE; }
// 3) Double-checked locking needs a volatile field
// Python: a module-level instance is already a singleton.
Check yourself 2 questions
  1. Why is the holder idiom thread-safe?

    Show answer

    Class loading initialises the holder once, safely.

  2. Alternative Java singleton?

    Show answer

    An enum with one instance.

Takeaway The holder idiom gives lazy, lock-free, thread-safe initialisation; an enum also works.

04LLD problem breakdowns & patterns

SystemDesign/06-lld/06-problems/* (Key takeaways), LLD_Interview_Cheatsheet.md, 03-design-patterns

LLD problems: pattern + the gotcha#

ProblemPatternsGotcha / key insight
Parking lotStrategy (spot allocation), Factory, SingletonParkingLot → ParkingFloor → ParkingSpot; delegate, don't god-class
Rate limiterStrategytoken bucket w/ lazy refill; ConcurrentHashMap per user
Tic-tac-toe—O(1) win check with row/col/diag counters
Vending machineStateno if-else state; polymorphic states
SplitwiseStrategy (split types)+ minimise cash flow greedy on net balances
BookMyShowStrategy, ObserverSeat vs ShowSeat; lock ShowSeat with TTL
ChessTemplate, Factorypieces validate geometry; Board validates path/check
Snake & ladder—single Jumper(start→end) class
ElevatorStrategy, StateSCAN/LOOK sweep with sorted sets, not FIFO
Comment systemCompositematerialised path for O(1) thread fetch
Hotel managementStrategy (pricing)date-range overlap in availability
ATMState, Chain (cash dispenser)external BankService does atomic debit
LRU cache—HashMap + DLL with dummy head/tail; know the wiring cold
Food deliveryStrategy (dispatch), Observer (status)focus on core models
LockerStrategysize ordering: S fits S/M/L/XL, L fits L/XL
NotificationStrategy, Observer, Factoryadd WhatsAppStrategy without touching core
Coupon systemStrategy / Rule enginecoupons as DB rows → strategy, never hardcode
LoggerChain of Responsibility, Strategy, Producer-ConsumerBlockingQueue for async
Library—Book vs BookItem (copies)
Order managementSaga / CommandOrderOrchestrator with compensating steps
Ride sharingStrategy (match, price), State (ride)black-box LocationService
Pub-subObserverBlockingQueue per topic + worker
Inventory—available vs reserved vs purchased quantity
Check yourself 2 questions
  1. Parking lot gotcha?

    Show answer

    Delegate through Lot → Floor → Spot; don't build a god class.

  2. Patterns for a parking lot?

    Show answer

    Strategy for spot allocation, Factory, Singleton.

Takeaway Each classic LLD problem has signature patterns and one gotcha.

Pattern trigger map (use at most 2)#

Trigger phrasePattern
multiple algorithms / pricing / payment typesStrategy
create objects by typeFactory
notify on change / subscribeObserver
single shared instance (config, registry)Singleton (thread-safe)
many optional paramsBuilder
add behaviour dynamically (toppings, filters)Decorator
behaviour depends on state (vending, ATM, order)State
undo / queue requestsCommand
pass through handlers (log levels, approvals)Chain of Responsibility
tree of parts (folders, comments)Composite
Check yourself 2 questions
  1. Why use at most two patterns?

    Show answer

    Over-patterning adds complexity without value.

  2. Single shared instance trigger?

    Show answer

    Singleton.

Takeaway Map trigger phrases to patterns, and use at most two per problem.

SOLID + scoring signals#

  • SRP one reason to change · OCP extend via new class · LSP subtypes substitutable · ISP small interfaces · DIP depend on abstractions
  • Composition over inheritance; facade service as the entry point
  • Value objects immutable (Money, Address); enums for statuses
  • Thread-safety stated explicitly; no global mutable state
  • Recovery line: "Let me simplify — I'll get the core flow working, then extend.
Check yourself 2 questions
  1. ISP in one line?

    Show answer

    Small, focused interfaces.

  2. What's the typical entry point to the design?

    Show answer

    A facade service.

Takeaway SOLID, composition over inheritance and a facade service as the entry point score well.

Class sketch: parking lot#

classDiagram
  class ParkingLot{+park(v) Ticket +unpark(t) Fee}
  class ParkingFloor{+findSpot(type) Spot}
  class ParkingSpot{+type +isFree()}
  class Ticket{+id +entryTime}
  class PricingStrategy{+fee(t)}
  ParkingLot "1" --> "*" ParkingFloor
  ParkingFloor "1" --> "*" ParkingSpot
  ParkingLot --> PricingStrategy
  ParkingLot --> Ticket
Check yourself 2 questions
  1. Who finds a free spot?

    Show answer

    ParkingFloor.findSpot(type).

  2. How is the fee computed?

    Show answer

    By a PricingStrategy.

Takeaway ParkingLot parks and unparks, floors find spots, tickets record entry, a pricing strategy computes fees.

05LLD problems: entities, APIs and the core move

For each classic problem: the classes to draw first, the methods to write first, and the part interviewers probe.

Problem playbook#

ProblemCore entitiesKey methodsPatternsWhat they probe
Parking lotParkingLot, Floor, Spot(type), Vehicle, Ticket, FeeCalculator, Gatepark(vehicle) → Ticket, unpark(ticket) → ReceiptStrategy (allocation, fees), Factory, SingletonConcurrent spot allocation; per-type free lists
ElevatorElevatorSystem, Elevator, Request, Direction, Dispatcher, Doorrequest(floor, dir), step()Strategy (dispatch), State (moving/idle/maintenance)SCAN/LOOK scheduling, choosing the nearest same-direction car
BookMyShow / movie bookingMovie, Theatre, Screen, Show, Seat, ShowSeat, Booking, PaymentholdSeats(show, seats), confirm(bookingId)Strategy (pricing), ObserverSeat hold with TTL; no double booking
SplitwiseUser, Group, Expense, Split (Equal/Exact/Percent), BalanceSheetaddExpense(), balances(user), settle()Strategy, FactoryValidate splits sum; simplify debts with heaps on net balance
Vending machineMachine, State, Inventory, Product, CoininsertCoin(), select(), dispense(), refund()StateIllegal transitions; change-making
ATMATM, Card, Account, Transaction, CashDispenser, BankServiceauthenticate(), withdraw(amount)State, Chain (note denominations)Atomic debit + dispense; reversal on failure
Library managementBook, BookItem(copy), Member, Loan, Reservation, Finecheckout(), return(), reserve()Observer (availability), Strategy (fines)Book vs BookItem; limits per member
ChessGame, Board, Cell, Piece(subtypes), Move, PlayermakeMove(from, to), isCheckmate()Template, Factory, Command (undo)Piece validates shape; board validates path and check
Tic-tac-toe (n×n)Game, Board, Player, Movemove(r, c) → result—O(1) win check using row/col/diagonal counters
Snake & ladderGame, Board, Jumper(start→end), Player, DiceplayTurn()Strategy (dice)One Jumper class covers snakes and ladders
LRU / LFU cacheCache, Node, DoublyLinkedList, (freq buckets)get(k), put(k, v) in O(1)Strategy (eviction)Map + DLL wiring; LFU min-freq tracking; thread safety
Rate limiterRateLimiter, Bucket, Rule, Clockallow(clientId) → boolStrategy (algorithm)Lazy refill; per-key locking; injectable clock
LoggerLogger, Level, Appender(console/file), Formatterlog(level, msg)Chain, Strategy, Singleton, Producer-ConsumerAsync appender with bounded queue; level filtering
Pub-sub / message queueBroker, Topic, Partition, Message, Publisher, Subscriber, Offsetpublish(topic, msg), subscribe(topic, s)ObserverPer-subscriber offsets; ordering; back-pressure
Hotel bookingHotel, Room(type), Booking, Guest, DateRange, Invoicesearch(range, type), book(), cancel()Strategy (pricing)Date-range overlap check; holds
Ride sharingRider, Driver, Trip(state), Location, Matcher, PricingrequestRide(), accept(), complete()Strategy, State, ObserverMatching nearest available driver atomically
Food deliveryRestaurant, Menu, Order(state), Cart, DeliveryAgent, DispatcherplaceOrder(), assignAgent(), track()State, Strategy, ObserverOrder lifecycle; reassignment on reject
File systemEntry (File / Directory), Path, Permissionsmkdir, ls, find(filter)Composite, SpecificationRecursive size; search filters composed with AND/OR
Task schedulerTask, Trigger(once/cron), Scheduler, Worker, DelayQueueschedule(task, at), cancel(id)Command, StrategyMin-heap by next run time; worker pool; retries
Shopping cart / inventoryProduct, Cart, CartItem, Inventory, Order, Couponadd(), checkout(), applyCoupon()Strategy, SpecificationReserve vs purchased stock; coupon stacking rules
Notification serviceNotification, Channel(Email/SMS/Push), Template, Preferencesend(userId, event)Strategy, Factory, ObserverAdd a channel without touching core; retries, dedup
Stack OverflowUser, Question, Answer, Comment, Vote, Tag, Reputationpost(), vote(), accept()Observer, CompositeOne vote per user; reputation updates
Cricket scoreboardMatch, Innings, Over, Ball, Player, ScorecardrecordBall(event)Observer, CommandExtras, wickets and strike rotation rules
Check yourself 2 questions
  1. Parking lot key methods?

    Show answer

    park(vehicle) → Ticket; unpark(ticket) → Receipt.

  2. What do interviewers probe in a rate limiter?

    Show answer

    Algorithm choice, concurrency and per-key state.

Takeaway For each problem know the core entities, key methods, patterns and what the interviewer is probing.

LRU cache, O(1) (Python)#

class Node:
    __slots__ = ("k", "v", "prev", "next")
    def __init__(self, k=0, v=0): self.k, self.v, self.prev, self.next = k, v, None, None

class LRUCache:
    def __init__(self, cap):
        self.cap, self.map = cap, {}
        self.head, self.tail = Node(), Node()          # sentinels
        self.head.next, self.tail.prev = self.tail, self.head
    def _remove(self, n): n.prev.next, n.next.prev = n.next, n.prev
    def _add_front(self, n):
        n.next, n.prev = self.head.next, self.head
        self.head.next.prev = n; self.head.next = n
    def get(self, k):
        if k not in self.map: return -1
        n = self.map[k]; self._remove(n); self._add_front(n); return n.v
    def put(self, k, v):
        if k in self.map: self._remove(self.map[k])
        n = self.map[k] = Node(k, v); self._add_front(n)
        if len(self.map) > self.cap:
            lru = self.tail.prev; self._remove(lru); del self.map[lru.k]
# Thread-safe: guard get/put with one lock (or striped locks per shard)
Check yourself 2 questions
  1. Data structures for an O(1) LRU?

    Show answer

    A hash map plus a doubly linked list.

  2. What happens on get?

    Show answer

    Move the node to the front (most recent).

Takeaway A hash map to nodes plus a doubly linked list with sentinels gives O(1) get and put.

Token-bucket rate limiter (Java, thread-safe)#

final class TokenBucket {
    private final long capacity; private final double refillPerNano;
    private double tokens; private long last;
    private final Clock clock;                       // injectable for tests
    TokenBucket(long cap, double perSec, Clock c){
        capacity = cap; refillPerNano = perSec / 1e9; tokens = cap; clock = c; last = c.nanos();
    }
    synchronized boolean tryAcquire(){
        long now = clock.nanos();
        tokens = Math.min(capacity, tokens + (now - last) * refillPerNano);  // lazy refill
        last = now;
        if (tokens < 1) return false;
        tokens -= 1; return true;
    }
}
class RateLimiter {
    private final ConcurrentHashMap<String, TokenBucket> buckets = new ConcurrentHashMap<>();
    boolean allow(String client){
        return buckets.computeIfAbsent(client, k -> new TokenBucket(10, 5, Clock.SYSTEM)).tryAcquire();
    }
}

Variants and follow-ups

  • Leaky bucket smooths output to a fixed rate; fixed window is simple but bursts at window edges.
  • Sliding log is exact but stores every timestamp; sliding window counter approximates it with two counters.
  • Distributed: keep the bucket in Redis and refill-and-take in one Lua script so it stays atomic.
  • Memory: per-client buckets need eviction (expire idle keys).
  • Response: return 429 with Retry-After computed from the token deficit.
Check yourself 2 questions
  1. How are tokens refilled?

    Show answer

    By elapsed time × refill rate, capped at capacity.

  2. Why inject a Clock?

    Show answer

    So tests can control time.

Takeaway Refill tokens by elapsed time, take one per request, synchronise access and inject a clock for tests.

Parking lot class sketch (Java)#

enum SpotType { MOTORBIKE, COMPACT, LARGE }
enum VehicleType { BIKE, CAR, TRUCK }
record Ticket(String id, String spotId, VehicleType type, Instant in) {}

interface SpotAllocator { Optional<Spot> allocate(VehicleType t); void release(Spot s); }
interface FeePolicy { Money fee(Ticket t, Instant out); }

final class ParkingLot {                       // facade
    private final SpotAllocator allocator; private final FeePolicy fees;
    private final Map<String, Ticket> active = new ConcurrentHashMap<>();
    Ticket park(Vehicle v){
        Spot s = allocator.allocate(v.type()).orElseThrow(LotFull::new);   // atomic inside
        Ticket t = new Ticket(UUID.randomUUID().toString(), s.id(), v.type(), Instant.now());
        active.put(t.id(), t); return t;
    }
    Receipt unpark(String ticketId){
        Ticket t = Optional.ofNullable(active.remove(ticketId)).orElseThrow(InvalidTicket::new);
        allocator.release(spotOf(t)); return new Receipt(t, fees.fee(t, Instant.now()));
    }
}
Check yourself 2 questions
  1. Why use a record for Ticket?

    Show answer

    It's an immutable value.

  2. What returns Optional in the sketch?

    Show answer

    The SpotAllocator, when no spot is free.

Takeaway Enums for spot and vehicle types, records for tickets, and an injectable SpotAllocator.

Tic-tac-toe with O(1) win check (Java)#

final class TicTacToe {
    private final int n;
    private final int[] rows, cols;
    private int diag, anti;
    TicTacToe(int n) { this.n = n; rows = new int[n]; cols = new int[n]; }

    /** player 1 or 2; returns the winner or 0. */
    int move(int r, int c, int player) {
        int d = player == 1 ? 1 : -1;
        rows[r] += d; cols[c] += d;
        if (r == c) diag += d;
        if (r + c == n - 1) anti += d;
        int target = d * n;
        return (rows[r] == target || cols[c] == target || diag == target || anti == target) ? player : 0;
    }
}
// Validation (occupied cell, wrong turn, game over) lives in a Game class around this.
Check yourself 2 questions
  1. How does the O(1) win check work?

    Show answer

    Add ±1 to the move's row, column and diagonals; |sum| = n means a win.

  2. Space needed?

    Show answer

    O(n): row and column arrays plus two diagonals.

Takeaway Track row, column and diagonal sums per player: a sum of ±n means a win, checked in O(1).

Logger with chain of responsibility (Java)#

enum Level { DEBUG, INFO, WARN, ERROR }

abstract class Handler {
    private Handler next;
    Handler then(Handler n) { this.next = n; return n; }
    void handle(Level lvl, String msg) {
        if (accepts(lvl)) write(lvl, msg);
        if (next != null) next.handle(lvl, msg);
    }
    abstract boolean accepts(Level lvl);
    abstract void write(Level lvl, String msg);
}
final class ConsoleHandler extends Handler {
    boolean accepts(Level l) { return l.compareTo(Level.INFO) >= 0; }
    void write(Level l, String m) { System.out.println(l + " " + m); }
}
final class AlertHandler extends Handler {
    boolean accepts(Level l) { return l == Level.ERROR; }
    void write(Level l, String m) { /* page on-call */ }
}
// chain: Handler root = new ConsoleHandler(); root.then(new AlertHandler());
// For throughput, put a BlockingQueue + writer thread in front (async appender).

Follow-ups

  • Async appender: a bounded queue plus one writer thread; decide whether to block or drop when it is full.
  • Configuration: levels per package, changeable at runtime without a restart.
  • Formatting is a Strategy; extra sinks (file, network) are more handlers in the chain.
  • Thread safety: a single writer thread, or synchronise each sink's write.
Check yourself 2 questions
  1. Which pattern routes log levels?

    Show answer

    Chain of Responsibility.

  2. How do handlers link?

    Show answer

    Each holds a next handler.

Takeaway Handlers handle levels they care about and pass messages down the chain.

In-memory pub-sub with per-subscriber offsets (Java)#

final class Topic {
    private final List<String> log = new CopyOnWriteArrayList<>();      // append-only
    void publish(String msg) { log.add(msg); }
    String read(int offset) { return offset < log.size() ? log.get(offset) : null; }
}

final class Subscriber implements Runnable {
    private final Topic topic; private final Consumer<String> handler;
    private final AtomicInteger offset = new AtomicInteger();             // own position
    private volatile boolean running = true;
    Subscriber(Topic t, Consumer<String> h) { topic = t; handler = h; }
    public void run() {
        while (running) {
            String m = topic.read(offset.get());
            if (m == null) { LockSupport.parkNanos(1_000_000); continue; }    // or wait/notify
            handler.accept(m);
            offset.incrementAndGet();                                    // commit after handling
        }
    }
    void resetOffset(int o) { offset.set(o); }                           // replay
    void stop() { running = false; }
}
// Each subscriber has its own offset, so slow ones don't block fast ones and can replay.
Check yourself 2 questions
  1. Why per-subscriber offsets?

    Show answer

    Each subscriber reads independently and can replay.

  2. What structure holds messages?

    Show answer

    An append-only list per topic.

Takeaway An append-only log per topic with per-subscriber offsets lets each consumer read at its own pace.

06Worked LLD designs: three walkthroughs and a booking flow

Requirements, class diagram, the code that interviewers actually probe, and the extensions to mention. Java, since most machine-coding rounds expect it.

Elevator system#

The core is a per-car scheduler (LOOK: keep going in one direction while stops remain) and a dispatcher that picks the cheapest car.

classDiagram
  class ElevatorSystem {
    +requestPickup(floor, dir)
    +requestStop(carId, floor)
    +tick()
  }
  class Dispatcher {
    <<interface>>
    +choose(cars, floor, dir) Elevator
  }
  class LeastCostDispatcher
  class Elevator {
    -int floor
    -Direction dir
    -TreeSet up
    -TreeSet down
    +addStop(floor)
    +step()
    +cost(floor, dir) int
  }
  class Direction {
    <<enumeration>>
    UP
    DOWN
    IDLE
  }
  ElevatorSystem "1" --> "*" Elevator
  ElevatorSystem --> Dispatcher
  Dispatcher <|.. LeastCostDispatcher
  Elevator --> Direction

Requirements to confirm

  • N cars, M floors; hall calls (floor + direction) and car calls (destination).
  • Minimise wait time; no starvation; doors, capacity and maintenance mode as extensions.
  • Single controller process; simulation driven by tick().

Key decisions

  • Two sorted sets per car (stops above, stops below) give O(log n) next-stop lookup.
  • Dispatcher is a Strategy: nearest car, least cost, zoning.
  • Car state (moving, doors open, maintenance) can become a State pattern.

Edge cases to test

  • A call for the current floor while the doors are open.
  • An opposite-direction hall call on the car's path: serve it only after the car turns.
  • Every car busy or in maintenance: queue the call, never drop it.
  • Repeated presses of the same button are idempotent.
  • Emergency stop or overweight: hold the car and re-dispatch its hall calls.

Follow-ups to expect

  • 100 floors and 8 cars: zone the building or add express cars.
  • Testing the scheduler: drive it with a fake clock and tick() so runs are deterministic.
  • Destination dispatch: riders enter the floor in the lobby, so you can group them by destination.

Elevator scheduling (LOOK)

enum Direction { UP, DOWN, IDLE }

final class Elevator {
    private int floor = 0;
    private Direction dir = Direction.IDLE;
    private final TreeSet<Integer> up = new TreeSet<>(), down = new TreeSet<>();

    synchronized void addStop(int f) {
        if (f > floor) up.add(f); else if (f < floor) down.add(f);
        if (dir == Direction.IDLE && f != floor) dir = f > floor ? Direction.UP : Direction.DOWN;
    }
    synchronized void step() {                  // one tick = one floor
        if (dir == Direction.UP) {
            if (up.isEmpty()) { dir = down.isEmpty() ? Direction.IDLE : Direction.DOWN; return; }
            floor++;
            if (up.remove(floor)) openDoors();
        } else if (dir == Direction.DOWN) {
            if (down.isEmpty()) { dir = up.isEmpty() ? Direction.IDLE : Direction.UP; return; }
            floor--;
            if (down.remove(floor)) openDoors();
        }
    }
    synchronized int cost(int f, Direction d) {   // lower is better
        int dist = Math.abs(floor - f);
        if (dir == Direction.IDLE) return dist;
        boolean onTheWay = (dir == Direction.UP && d == Direction.UP && f >= floor)
                        || (dir == Direction.DOWN && d == Direction.DOWN && f <= floor);
        return onTheWay ? dist : dist + 100;      // penalise turning around
    }
    private void openDoors() { /* notify observers, start door timer */ }
}

Dispatcher

interface Dispatcher { Elevator choose(List<Elevator> cars, int floor, Direction d); }

final class LeastCostDispatcher implements Dispatcher {
    public Elevator choose(List<Elevator> cars, int floor, Direction d) {
        return cars.stream().min(Comparator.comparingInt(c -> c.cost(floor, d))).orElseThrow();
    }
}

Extensions to mention

  • Capacity: skip hall calls when the car is full.
  • Peak modes: park idle cars at the lobby in the morning.
  • Fairness: age requests so far floors aren't starved.
  • Concurrency: requests arrive on many threads; each car's state is guarded by its own lock.
Check yourself 2 questions
  1. What does the LOOK algorithm do?

    Show answer

    Keeps moving in one direction while stops remain, then reverses.

  2. What does the dispatcher choose?

    Show answer

    The cheapest car for each pickup request.

Takeaway A per-car LOOK scheduler plus a dispatcher that picks the cheapest car.

Movie ticket booking (BookMyShow)#

Model a seat per show separately from the physical seat, and make "hold these seats" all-or-nothing with an expiry.

classDiagram
  class Show {
    +String id
    +Movie movie
    +Screen screen
    +Instant start
  }
  class Seat {
    +String id
    +SeatType type
  }
  class ShowSeat {
    +Seat seat
    +SeatStatus status
    +Money price
  }
  class Booking {
    +String id
    +String userId
    +List seats
    +BookingStatus status
  }
  class BookingService {
    +hold(showId, seatIds, userId) Hold
    +confirm(holdId, payment) Booking
  }
  class SeatLockProvider {
    <<interface>>
    +lock(showId, seatIds, userId) bool
    +unlock(showId, seatIds, userId)
  }
  Show "1" --> "*" ShowSeat
  ShowSeat --> Seat
  BookingService --> SeatLockProvider
  BookingService --> Booking
  Booking --> ShowSeat

Requirements to confirm

  • Search shows by city/movie; view seat layout; select up to N seats; hold for 10 minutes; pay; confirm or release.
  • No double booking under concurrent requests; price by seat type and show.

Key decisions

  • Seat vs ShowSeat: the physical seat is shared across shows; status lives on ShowSeat.
  • Locking behind an interface: in-memory for the interview, Redis or DB in production.
  • Pricing as a Strategy (weekday, premium, surge); notifications via Observer.
  • Money as integer minor units, never double.

All-or-nothing seat lock with expiry

final class InMemorySeatLock implements SeatLockProvider {
    private record Lock(String user, Instant expiry) {}
    private final Map<String, Map<String, Lock>> locks = new ConcurrentHashMap<>();
    private final Duration ttl; private final Clock clock;
    InMemorySeatLock(Duration ttl, Clock clock) { this.ttl = ttl; this.clock = clock; }

    public boolean lock(String show, List<String> seats, String user) {
        Map<String, Lock> m = locks.computeIfAbsent(show, k -> new HashMap<>());
        synchronized (m) {                         // serialise per show only
            Instant now = clock.instant();
            for (String s : seats) {
                Lock l = m.get(s);
                if (l != null && l.expiry().isAfter(now) && !l.user().equals(user)) return false;
            }
            for (String s : seats) m.put(s, new Lock(user, now.plus(ttl)));
            return true;
        }
    }
    public void unlock(String show, List<String> seats, String user) {
        Map<String, Lock> m = locks.get(show); if (m == null) return;
        synchronized (m) { seats.forEach(s -> m.computeIfPresent(s, (k, l) -> l.user().equals(user) ? null : l)); }
    }
}

Confirm flow

  1. Check every seat is still locked by this user (not expired).
  2. Charge with an idempotency key.
  3. Mark ShowSeats BOOKED and save the booking in one transaction.
  4. Unlock; publish a BookingConfirmed event.
  5. On payment failure or timeout, release the lock and mark the booking FAILED.

Extensions to mention

  • Distributed lock: Redis SET key NX PX per seat, with the DB unique constraint as a safety net.
  • Waitlist via Observer when seats free up.
  • Coupons as a rule engine.
Check yourself 2 questions
  1. Why model ShowSeat separately from Seat?

    Show answer

    Availability is per show, not per physical seat.

  2. How are holds made safe?

    Show answer

    All-or-nothing locking with an expiry.

Takeaway Model seat-per-show separately from the physical seat; holds are all-or-nothing with expiry.

Splitwise (expense sharing)#

Different split types are a Strategy with validation, balances are a ledger, and "settle up" is a greedy matching of debtors and creditors.

classDiagram
  class ExpenseService {
    +addExpense(groupId, paidBy, amount, splitType, details)
    +balances(userId) Map
    +settlePlan(groupId) List
  }
  class Expense {
    +String id
    +String paidBy
    +long amountCents
    +List splits
  }
  class Split {
    <<abstract>>
    +String userId
    +long amountCents
  }
  class SplitStrategy {
    <<interface>>
    +compute(amount, users, details) List
  }
  class EqualSplit
  class ExactSplit
  class PercentSplit
  class BalanceSheet {
    +apply(Expense)
    +net(userId) long
  }
  ExpenseService --> SplitStrategy
  ExpenseService --> BalanceSheet
  Expense "1" --> "*" Split
  SplitStrategy <|.. EqualSplit
  SplitStrategy <|.. ExactSplit
  SplitStrategy <|.. PercentSplit

Requirements to confirm

  • Users, groups, expenses paid by one user split equally, by exact amounts or by percentages.
  • Show who owes whom; simplify debts to few transfers; record settlements.

Key decisions

  • Store money as long cents; give rounding remainders to the first participants deterministically.
  • Each strategy validates its input (exact amounts sum to the total; percentages sum to 100).
  • Balances as net amount per user per group: positive is owed money, negative owes.
  • Expenses are immutable; edits are reversal plus a new expense (audit trail).

Equal split with fair rounding

final class EqualSplit implements SplitStrategy {
    public List<Split> compute(long amount, List<String> users, Map<String, Long> ignored) {
        long base = amount / users.size(), rem = amount % users.size();
        List<Split> out = new ArrayList<>();
        for (int i = 0; i < users.size(); i++)
            out.add(new Split(users.get(i), base + (i < rem ? 1 : 0)));
        return out;                               // sums exactly to amount
    }
}

Simplify debts

record Transfer(String from, String to, long cents) {}

static List<Transfer> simplify(Map<String, Long> net) {   // + owed, − owes
    PriorityQueue<long[]> cred = new PriorityQueue<>((a, b) -> Long.compare(b[1], a[1]));
    PriorityQueue<long[]> debt = new PriorityQueue<>((a, b) -> Long.compare(b[1], a[1]));
    List<String> ids = new ArrayList<>(net.keySet());
    for (int i = 0; i < ids.size(); i++) {
        long v = net.get(ids.get(i));
        if (v > 0) cred.add(new long[]{i, v}); else if (v < 0) debt.add(new long[]{i, -v});
    }
    List<Transfer> out = new ArrayList<>();
    while (!cred.isEmpty() && !debt.isEmpty()) {
        long[] c = cred.poll(), d = debt.poll();
        long amt = Math.min(c[1], d[1]);
        out.add(new Transfer(ids.get((int) d[0]), ids.get((int) c[0]), amt));
        if (c[1] > amt) cred.add(new long[]{c[0], c[1] - amt});
        if (d[1] > amt) debt.add(new long[]{d[0], d[1] - amt});
    }
    return out;   // at most n − 1 transfers; the true minimum is NP-hard
}
Check yourself 2 questions
  1. Pattern for equal, exact and percent splits?

    Show answer

    Strategy, each with validation.

  2. How does settle-up minimise transactions?

    Show answer

    Greedily match largest debtors with largest creditors.

Takeaway Split types are strategies with validation, balances are a ledger, and settle-up greedily matches debtors and creditors.

Booking flow as a sequence diagram#

sequenceDiagram
  participant U as User
  participant BS as BookingService
  participant L as SeatLockProvider
  participant P as PaymentGateway
  participant R as BookingRepository
  U->>BS: hold(showId, seats)
  BS->>L: lock(showId, seats, userId)
  L-->>BS: locked until T + 10 min
  BS-->>U: holdId
  U->>BS: confirm(holdId, paymentToken)
  BS->>L: still locked by this user?
  BS->>P: charge(amount, idempotencyKey)
  P-->>BS: success
  BS->>R: save booking and mark seats BOOKED
  BS->>L: unlock(showId, seats)
  BS-->>U: booking confirmed

Draw this after the class diagram: it proves the classes can actually carry out the use case and shows where the concurrency risk sits (between lock and confirm).

Check yourself 2 questions
  1. What happens if payment fails?

    Show answer

    Release the seat locks.

  2. When is the booking saved?

    Show answer

    After successful payment, via the repository.

Takeaway Hold seats with a lock provider, pay, then confirm and save; release locks on failure.

07Concurrency, atomicity & error paths

Correctness boundary#

ProblemMechanismInvariant
Concurrent map updateAtomic map op / lockCheck-and-set is one operation.
Shared counterAtomic integer / synchronized allocatorNo lost or duplicate increments.
Multi-field transitionLock or database transactionNo partial state visible.
Work queueBlockingQueue / bounded channelBackpressure and shutdown are defined.
Retryable commandIdempotency key + stored resultRetry returns same logical outcome.
External side effectOutbox / saga boundaryFailure can be retried or compensated.
Check yourself 2 questions
  1. Concurrent map update mechanism?

    Show answer

    An atomic map operation (e.g. computeIfAbsent) or a lock.

  2. Shared counter mechanism?

    Show answer

    An atomic integer or a synchronised allocator.

Takeaway Make check-and-set one operation: atomic map ops, atomic counters, locks or transactions.

Review questions#

  • Who owns each mutable field?
  • Can two requests race on the same object?
  • What makes each method atomic?
  • Can a retry duplicate an operation?
  • Are terminal and invalid states explicit?
  • Can dependencies be replaced in a unit test?
Check yourself 2 questions
  1. Name a concurrency review question.

    Show answer

    Any of: who owns each mutable field, can two requests race, what makes the method atomic.

  2. Why ask whether retries duplicate operations?

    Show answer

    Retries without idempotency cause double effects.

Takeaway Ask who owns each field, what races, what makes methods atomic, whether retries duplicate, and which states are terminal.

Optimistic vs pessimistic locking in code#

// Pessimistic: hold a lock for the whole read-modify-write
synchronized (account) { account.debit(amount); }

// Optimistic in memory: compare-and-swap loop
AtomicReference<Balance> ref = new AtomicReference<>(start);
while (true) {
    Balance cur = ref.get();
    Balance next = cur.minus(amount);           // immutable value
    if (ref.compareAndSet(cur, next)) break;    // retry if someone else won
}

// Optimistic in the database: version column
// UPDATE accounts SET balance = ?, version = version + 1
//  WHERE id = ? AND version = ?   -- 0 rows updated means retry
  • Optimistic wins when conflicts are rare; pessimistic when contention is high or retries are expensive.
  • Avoid deadlock under pessimistic locking: acquire locks in a global order (for example by account ID) or use tryLock with a timeout.
  • CAS can suffer the ABA problem; use a versioned reference such as AtomicStampedReference.
Check yourself 2 questions
  1. When prefer optimistic locking?

    Show answer

    Low contention.

  2. What does the optimistic loop use?

    Show answer

    Compare-and-swap, retrying on conflict.

Takeaway Pessimistic holds a lock for the whole read-modify-write; optimistic retries a compare-and-swap.

08Concurrency toolkit

Machine-coding rounds increasingly ask "make it thread-safe". Know the primitive, the hazard it prevents, and the classic exercises.

Primitives: Java and Python#

NeedJavaPython
Mutual exclusionsynchronized, ReentrantLock (tryLock, fairness)threading.Lock / RLock
Many readers, one writerReentrantReadWriteLock, StampedLockLock + Condition (no built-in RW lock)
Limit concurrent accessSemaphorethreading.Semaphore
Wait for a conditionCondition.await/signal, wait/notifyAllthreading.Condition, Event
Lock-free counterAtomicInteger, LongAdder (CAS)Lock (GIL doesn't make += atomic)
Visibilityvolatile, happens-before—
Concurrent mapConcurrentHashMap.compute/mergedict + Lock
Hand-off queueBlockingQueue (Array/Linked), DelayQueuequeue.Queue, PriorityQueue
Wait for N tasksCountDownLatch, CyclicBarrier, PhaserBarrier, concurrent.futures.wait
Thread poolExecutorService, CompletableFuture, virtual threads (21+)ThreadPoolExecutor, ProcessPoolExecutor, asyncio
Python GIL: threads help I/O-bound work; use processes for CPU-bound work. Free-threaded builds exist from 3.13 but are optional.
Check yourself 2 questions
  1. Many readers, one writer in Java?

    Show answer

    ReentrantReadWriteLock or StampedLock.

  2. Mutual exclusion in Python?

    Show answer

    threading.Lock or RLock.

Takeaway Locks, read-write locks, conditions, semaphores, atomics and concurrent collections in both languages.

Hazards and how to prevent them#

HazardLooks likePrevention
Race conditioncheck-then-act, read-modify-writeAtomic op (CAS, computeIfAbsent) or one lock around both steps
DeadlockTwo threads hold locks the other needsGlobal lock ordering, tryLock with timeout, fewer locks
LivelockThreads keep yielding to each otherRandomised back-off
StarvationA thread never gets the lockFair locks, bounded priorities
Visibility bugThread never sees a flag changevolatile, locks, atomics
Lost updateTwo writers overwrite each otherOptimistic version check or row lock
ABACAS succeeds on a recycled valueVersioned/stamped references
Priority inversionLow-priority holder blocks high priorityPriority inheritance, short critical sections
Coffman conditions for deadlock: mutual exclusion, hold-and-wait, no preemption, circular wait. Break any one, usually circular wait via ordering.
Check yourself 2 questions
  1. How do you prevent deadlock?

    Show answer

    Acquire locks in a global order, or use tryLock with timeouts.

  2. Fix a check-then-act race?

    Show answer

    An atomic operation or one lock around both steps.

Takeaway Races, deadlocks, livelocks, starvation and visibility bugs each have a prevention.

Classic concurrency exercises#

ProblemCore idea
Producer–consumer / bounded blocking queueLock + two conditions (notFull, notEmpty); loop on the predicate
Readers–writersRW lock; decide reader vs writer preference
Dining philosophersOrder the forks or limit diners with a semaphore of N−1
Print in order / FooBar / ZeroEvenOddSemaphores or condition hand-off between threads
Building H₂OSemaphores (2 H, 1 O) + barrier
Multithreaded web crawlerConcurrent visited set + work queue + pool; stop when queue empty and no task in flight
Thread-safe LRU cacheOne lock, or segment the key space into shards
Delayed task schedulerPriority queue + condition wait until the earliest deadline
Check yourself 2 questions
  1. Producer–consumer core idea?

    Show answer

    A lock with two conditions (notFull, notEmpty), looping on the predicate.

  2. Why loop on the predicate, not if?

    Show answer

    Spurious wakeups.

Takeaway Producer–consumer, readers–writers, dining philosophers and ordered printing are the classics.

Bounded blocking queue (Python)#

import threading
from collections import deque

class BoundedBlockingQueue:
    def __init__(self, capacity):
        self.q, self.cap = deque(), capacity
        self.lock = threading.Lock()
        self.not_full = threading.Condition(self.lock)
        self.not_empty = threading.Condition(self.lock)
    def enqueue(self, x):
        with self.not_full:
            while len(self.q) == self.cap:      # while, not if: spurious wake-ups
                self.not_full.wait()
            self.q.append(x)
            self.not_empty.notify()
    def dequeue(self):
        with self.not_empty:
            while not self.q:
                self.not_empty.wait()
            x = self.q.popleft()
            self.not_full.notify()
            return x
Check yourself 2 questions
  1. When does put() wait?

    Show answer

    While the queue is full.

  2. What does take() signal after removing?

    Show answer

    notFull, waking a producer.

Takeaway A deque, a lock and two conditions; producers wait when full, consumers when empty.

Producer–consumer with a bounded queue#

flowchart TD
  P1["Producer 1"] --> Q[["Bounded blocking queue<br/>capacity N"]]
  P2["Producer 2"] --> Q
  Q --> W1["Consumer 1"]
  Q --> W2["Consumer 2"]
  Q -.->|"full: producers block"| P1
  W1 -.->|"empty: consumers wait"| Q

The bound gives back-pressure; a poison pill or shutdown flag stops consumers cleanly.

Check yourself 2 questions
  1. What happens when the queue is full?

    Show answer

    Producers block.

  2. Why bound the queue?

    Show answer

    Backpressure, to cap memory and slow producers.

Takeaway A bounded queue gives backpressure: producers block when full, consumers when empty.

09Machine-coding round: structure, APIs, errors, tests

Machine-coding rounds (90–120 minutes, runnable code) reward a clean package layout, a working demo and easy extension more than clever algorithms.

Time plan (90 min)#

MinDo
0–10Clarify scope; write the 4–6 must-have commands
10–20Models (enums, value objects, entities) and interfaces
20–65Services for the happy path; in-memory repositories
65–80Driver/demo with the sample input; validation and exceptions
80–90Extension point demo, concurrency note, cleanup
Check yourself 2 questions
  1. What happens in minutes 0–10?

    Show answer

    Clarify scope and write the 4–6 must-have commands.

  2. Where does most time go?

    Show answer

    Services for the happy path, about minutes 20–65.

Takeaway Clarify and list commands, models and interfaces, happy-path services, then edge cases, tests and demo.

Package layout#

app/
  model/        # entities, value objects, enums
  repository/   # interfaces + in-memory impls
  service/      # use cases (facade per aggregate)
  strategy/     # pluggable rules (pricing, matching)
  exception/    # domain exceptions
  Main          # driver: parses commands, prints output
  • Keep I/O in the driver only; services return values.
  • One public method per use case.
Check yourself 2 questions
  1. Where do pluggable rules go?

    Show answer

    The strategy package.

  2. Where do in-memory implementations live?

    Show answer

    Under repository.

Takeaway model, repository, service, strategy, exception and a main or demo package.

Evaluation rubric#

  • Runs end-to-end on the sample input
  • Separation of concerns; no god class
  • Extensible: a new type means a new class
  • Meaningful names, small methods, no dead code
  • Edge cases and errors handled explicitly
  • Thread-safety called out where state is shared
  • Tests or a demo that proves behaviour
Check yourself 2 questions
  1. What shows extensibility?

    Show answer

    A new type means a new class, not edits.

  2. First thing on the rubric?

    Show answer

    It runs end to end on the sample input.

Takeaway Runs end to end, separated concerns, extensible, clean names, edge cases and tests.

API and method design#

  • Methods are verbs in domain language: reserve(), settle().
  • Return domain objects or results, never raw maps.
  • Validate inputs at the boundary; constructors enforce invariants.
  • Prefer immutable inputs and outputs (records, frozen dataclasses).
  • Idempotent where retries are possible: pass a request ID.
  • Pagination and filtering for list methods.
Check yourself 2 questions
  1. What should methods return?

    Show answer

    Domain objects or results, never raw maps.

  2. Where should inputs be validated?

    Show answer

    At the boundary; constructors enforce invariants.

Takeaway Verb methods in domain language, domain return types, validation at boundaries, immutable values.

Errors and edge cases#

  • Domain exceptions (SeatUnavailable, InsufficientFunds) over generic ones.
  • Decide: exception, Optional, or result type. Be consistent.
  • Check: empty input, duplicates, not found, capacity full, invalid transition, concurrent conflict, partial failure.
  • Roll back or compensate on partial failure; never leave half-updated state.
Check yourself 2 questions
  1. Domain exception examples?

    Show answer

    SeatUnavailable, InsufficientFunds.

  2. Name three edge cases to check.

    Show answer

    Any three of: empty input, duplicates, not found, capacity limits, concurrent access.

Takeaway Domain exceptions, a consistent error style, and checks for empty, duplicate, missing and capacity cases.

Testing the design#

  • DIP pays off here: inject fakes for clock, repository, payment gateway.
  • Unit-test each strategy and each state transition.
  • Table-driven tests for rules (fees, splits, discounts).
  • Concurrency test: N threads booking one seat → exactly one succeeds.
  • Say which tests you would write even if time runs out.
Check yourself 2 questions
  1. How does DIP help testing?

    Show answer

    You can inject fakes for clock, repository and payment gateway.

  2. What suits fee or split rules?

    Show answer

    Table-driven tests.

Takeaway Inject fakes, unit-test strategies and transitions, use table-driven tests, and test concurrency.

10LLD last-minute checklist

LLD last-minute checklist#

  • Confirm use cases before drawing classes.
  • State invariants and who owns each piece of state.
  • Separate entities, immutable values, services, and gateways.
  • Define method signatures before implementation details.
  • Use composition; choose at most two useful patterns.
  • Make state transitions and invalid transitions explicit.
  • State thread-safety and transaction boundaries.
  • Dry-run normal, duplicate, invalid, concurrent, and failure cases.
Check yourself 2 questions
  1. What comes before drawing classes?

    Show answer

    Confirming use cases.

  2. What should be stated for each piece of state?

    Show answer

    Its invariants and owner.

Takeaway Confirm use cases, state invariants and ownership, separate building blocks, define signatures, then code.

No cards match. Try fewer or different words, or press Esc to clear.