{}DSA Atlas

LLD Case Studies I — Parking Lot, Elevator, Vending Machine

Three of the most-asked LLD problems solved end to end — requirements, class diagram, key flows, design decisions, thread-safe Java code, and the follow-up questions interviewers ask.

Intermediate → Advanced4 interview questions

1. Parking lot

Requirements

  1. A lot has multiple floors; each floor has spots of types compact, regular, large, EV, motorcycle.
  2. Vehicles: motorcycle, car, van/truck (and EV cars).
  3. Multiple entry and exit gates operate concurrently.
  4. On entry: find a suitable free spot, issue a ticket. On exit: compute the fee, take payment, free the spot.
  5. Pricing differs by vehicle type and duration (hourly with first-hour rate); pluggable.
  6. Display free spots per floor and type.

Out of scope (state it): reservations, license-plate recognition, persistence.

Class diagram

ParkingLotfloors, gatespark() · exit() Floorfree spot queuesby SpotType Spotid, typetryOccupy() / release() Ticketvehicle, spot,entryTime, status Vehicleplate, VehicleType «interface»PricingStrategyfee(ticket, exitTime) «interface»SpotAllocationStrategyallocate(type, floors) 1 → * 1 → * enums: VehicleType, SpotType, TicketStatus · services: ParkingService, PaymentService
Allocation and pricing are strategies; spots claim themselves atomically.

Key decisions

  • Compatibility table maps vehicle types to acceptable spot types in preference order (a motorcycle can use motorcycle → compact → regular).
  • Free spots kept in concurrent queues per floor and spot type → O(1) allocation, no global lock.
  • Strategies for allocation (lowest floor first, nearest to gate) and pricing.
  • Clock injected for testable pricing.

Code

Java
enum VehicleType { MOTORCYCLE, CAR, VAN }
enum SpotType { MOTORCYCLE, COMPACT, REGULAR, LARGE, EV }
enum TicketStatus { ACTIVE, PAID }

record Vehicle(String plate, VehicleType type, boolean electric) {}

final class Spot {
    final String id; final SpotType type; final int floor;
    private final AtomicReference<Vehicle> occupant = new AtomicReference<>();
    Spot(String id, SpotType type, int floor) { this.id = id; this.type = type; this.floor = floor; }
    boolean tryOccupy(Vehicle v) { return occupant.compareAndSet(null, v); }
    void release() { occupant.set(null); }
}

final class Floor {
    final int number;
    private final Map<SpotType, ConcurrentLinkedQueue<Spot>> free = new EnumMap<>(SpotType.class);
    Floor(int number, List<Spot> spots) {
        this.number = number;
        for (SpotType t : SpotType.values()) free.put(t, new ConcurrentLinkedQueue<>());
        spots.forEach(s -> free.get(s.type).add(s));
    }
    Optional<Spot> take(SpotType t, Vehicle v) {
        Spot s;
        while ((s = free.get(t).poll()) != null) {      // poll() is atomic: no two threads get the same spot
            if (s.tryOccupy(v)) return Optional.of(s);
        }
        return Optional.empty();
    }
    void giveBack(Spot s) { s.release(); free.get(s.type).add(s); }
    int available(SpotType t) { return free.get(t).size(); }
}

final class Ticket {
    final String id; final Vehicle vehicle; final Spot spot; final Instant entry;
    volatile TicketStatus status = TicketStatus.ACTIVE;
    Ticket(String id, Vehicle v, Spot s, Instant entry) { this.id = id; this.vehicle = v; this.spot = s; this.entry = entry; }
}

interface PricingStrategy { long fee(Ticket t, Instant exit); }

final class HourlyPricing implements PricingStrategy {
    private final Map<VehicleType, long[]> rates = Map.of(        // {first hour, each extra hour} in paise
        VehicleType.MOTORCYCLE, new long[]{2000, 1000},
        VehicleType.CAR, new long[]{5000, 3000},
        VehicleType.VAN, new long[]{8000, 5000});
    public long fee(Ticket t, Instant exit) {
        long minutes = Math.max(1, Duration.between(t.entry, exit).toMinutes());
        long hours = (minutes + 59) / 60;                          // round up
        long[] r = rates.get(t.vehicle.type());
        return r[0] + (hours - 1) * r[1];
    }
}

interface SpotAllocationStrategy { Optional<Spot> allocate(Vehicle v, List<Floor> floors); }

final class LowestFloorFirst implements SpotAllocationStrategy {
    private static final Map<VehicleType, List<SpotType>> COMPATIBLE = Map.of(
        VehicleType.MOTORCYCLE, List.of(SpotType.MOTORCYCLE, SpotType.COMPACT, SpotType.REGULAR),
        VehicleType.CAR, List.of(SpotType.COMPACT, SpotType.REGULAR, SpotType.LARGE),
        VehicleType.VAN, List.of(SpotType.LARGE));
    public Optional<Spot> allocate(Vehicle v, List<Floor> floors) {
        List<SpotType> prefs = new ArrayList<>(COMPATIBLE.get(v.type()));
        if (v.electric()) prefs.add(0, SpotType.EV);                 // EVs prefer charging spots
        for (Floor f : floors)
            for (SpotType t : prefs) {
                Optional<Spot> s = f.take(t, v);
                if (s.isPresent()) return s;
            }
        return Optional.empty();
    }
}

final class ParkingLot {
    private final List<Floor> floors;
    private final SpotAllocationStrategy allocator;
    private final PricingStrategy pricing;
    private final Clock clock;
    private final Map<String, Ticket> active = new ConcurrentHashMap<>();
    private final AtomicLong seq = new AtomicLong();

    ParkingLot(List<Floor> floors, SpotAllocationStrategy a, PricingStrategy p, Clock c) {
        this.floors = floors; this.allocator = a; this.pricing = p; this.clock = c;
    }

    Ticket park(Vehicle v) {
        Spot spot = allocator.allocate(v, floors)
            .orElseThrow(() -> new IllegalStateException("lot full for " + v.type()));
        Ticket t = new Ticket("T" + seq.incrementAndGet(), v, spot, clock.instant());
        active.put(t.id, t);
        return t;
    }

    long exit(String ticketId, PaymentProcessor payments) {
        Ticket t = active.remove(ticketId);                              // atomic: a ticket exits once
        if (t == null) throw new IllegalArgumentException("unknown or used ticket");
        long fee = pricing.fee(t, clock.instant());
        payments.collect(t.vehicle.plate(), fee);
        t.status = TicketStatus.PAID;
        floors.get(t.spot.floor).giveBack(t.spot);
        return fee;
    }
}

Follow-ups interviewers ask

  • Lost ticket? Charge a daily maximum; look up by plate.
  • Display boards? Floor publishes availability changes to observers.
  • Reservations? A Reservation holds a spot with an expiry; the allocator skips reserved spots.
  • Distributed / multiple lots? Persist spots in a DB, claim with conditional updates; this becomes an HLD question.

2. Elevator system

Requirements

  1. N elevators, F floors; hall calls (floor + up/down) and car calls (destination buttons inside).
  2. A dispatcher assigns hall calls to elevators efficiently.
  3. Elevators move one floor per tick, open doors at stops, respect capacity.
  4. States: idle, moving up, moving down, doors open, maintenance.

Design

Hall buttons(floor, direction) DispatcherDispatchStrategy(nearest-car cost) Elevator 1state · upStops · downStops Elevator 2LOOK scheduling inside Elevator 3car buttons → addStop()
Dispatcher picks an elevator per hall call; each elevator orders its own stops (LOOK).

Code (core)

Java
enum Direction { UP, DOWN, IDLE }

final class Elevator {
    final int id;
    private int floor = 0;
    private Direction direction = Direction.IDLE;
    private final TreeSet<Integer> upStops = new TreeSet<>();
    private final TreeSet<Integer> downStops = new TreeSet<>(Comparator.reverseOrder());

    Elevator(int id) { this.id = id; }

    synchronized void addStop(int target) {
        if (target > floor) upStops.add(target);
        else if (target < floor) downStops.add(target);
        if (direction == Direction.IDLE) direction = target >= floor ? Direction.UP : Direction.DOWN;
    }

    /** Advance one tick using LOOK: keep going in the current direction while stops remain. */
    synchronized void step() {
        if (direction == Direction.UP) {
            if (upStops.isEmpty()) { direction = downStops.isEmpty() ? Direction.IDLE : Direction.DOWN; return; }
            floor++;
            if (upStops.remove(floor)) openDoors();
        } else if (direction == Direction.DOWN) {
            if (downStops.isEmpty()) { direction = upStops.isEmpty() ? Direction.IDLE : Direction.UP; return; }
            floor--;
            if (downStops.remove(floor)) openDoors();
        }
    }

    synchronized int cost(int callFloor, Direction callDir) {
        if (direction == Direction.IDLE) return Math.abs(floor - callFloor);
        boolean onTheWay = (direction == Direction.UP && callDir == Direction.UP && callFloor >= floor)
                        || (direction == Direction.DOWN && callDir == Direction.DOWN && callFloor <= floor);
        if (onTheWay) return Math.abs(floor - callFloor);
        int turn = direction == Direction.UP
            ? (upStops.isEmpty() ? floor : upStops.last())
            : (downStops.isEmpty() ? floor : downStops.last());
        return Math.abs(floor - turn) + Math.abs(turn - callFloor) + 5;   // penalty for reversing
    }

    private void openDoors() { /* notify observers, wait, close */ }
}

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

final class NearestCarStrategy implements DispatchStrategy {
    public Elevator choose(List<Elevator> cars, int floor, Direction dir) {
        return cars.stream().min(Comparator.comparingInt(e -> e.cost(floor, dir))).orElseThrow();
    }
}

final class ElevatorController {
    private final List<Elevator> cars;
    private final DispatchStrategy strategy;
    ElevatorController(List<Elevator> cars, DispatchStrategy s) { this.cars = cars; this.strategy = s; }

    void hallCall(int floor, Direction dir) { strategy.choose(cars, floor, dir).addStop(floor); }
    void carCall(int elevatorId, int floor) { cars.get(elevatorId).addStop(floor); }
    void tick() { cars.forEach(Elevator::step); }      // driven by a scheduler thread
}

Extensions: capacity/weight sensors, State pattern for door/maintenance/emergency states, peak-hour strategies, destination dispatch, Observer for floor displays.

3. Vending machine

Requirements

  1. Products in slots with prices and quantities.
  2. Accept coins/notes; select a product; dispense it and return change.
  3. Cancel/refund before dispensing; handle out-of-stock and insufficient change.

State diagram

Idle HasMoney Dispensing insert insert more select (enough $) dispensed + change returned cancel → refund
Each state class handles every event — invalid ones are rejected explicitly.
Java
interface VendingState {
    default VendingState insert(Machine m, int amount) { throw new IllegalStateException("can't insert now"); }
    default VendingState select(Machine m, String slot) { throw new IllegalStateException("can't select now"); }
    default VendingState cancel(Machine m) { throw new IllegalStateException("nothing to cancel"); }
}

final class Idle implements VendingState {
    public VendingState insert(Machine m, int amount) { m.addBalance(amount); return new HasMoney(); }
}

final class HasMoney implements VendingState {
    public VendingState insert(Machine m, int amount) { m.addBalance(amount); return this; }
    public VendingState cancel(Machine m) { m.refundAll(); return new Idle(); }
    public VendingState select(Machine m, String slot) {
        Product p = m.inventory().peek(slot);
        if (p == null) throw new IllegalStateException("out of stock");
        if (m.balance() < p.price()) throw new IllegalStateException("insert " + (p.price() - m.balance()) + " more");
        Map<Integer, Integer> change = m.cashbox().makeChange(m.balance() - p.price())
            .orElseThrow(() -> new IllegalStateException("exact change only"));
        m.inventory().take(slot);
        m.dispense(p, change);                       // physical dispense, then
        return new Idle();                           // balance reset inside dispense
    }
}

final class Machine {
    private VendingState state = new Idle();
    private int balance;
    private final Inventory inventory; private final CashBox cashbox;
    Machine(Inventory i, CashBox c) { this.inventory = i; this.cashbox = c; }

    synchronized void insert(int amount) { state = state.insert(this, amount); }   // one customer at a time
    synchronized void select(String slot) { state = state.select(this, slot); }
    synchronized void cancel() { state = state.cancel(this); }

    void addBalance(int a) { balance += a; cashbox.accept(a); }
    int balance() { return balance; }
    void refundAll() { cashbox.makeChange(balance).ifPresent(this::eject); balance = 0; }
    void dispense(Product p, Map<Integer, Integer> change) { eject(change); balance = 0; }
    Inventory inventory() { return inventory; } CashBox cashbox() { return cashbox; }
    private void eject(Map<Integer, Integer> coins) { /* hardware */ }
}

Change-making: greedy works for canonical coin systems (1, 2, 5, 10…) given unlimited coins; with limited coin counts greedy can fail even then, so use a bounded DP over available coins (see Knapsack).

Interview questions

0 / 4 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.