Load/Bearing
Low-level design · 20 of 22

Parking lot in 90 minutes

The classic LLD problem: clarify, model the entities, leave an extension point, and handle two cars racing for the last spot.

4 min read

The parking lot tests whether you can turn a vague prompt into a clean object model and working code within the time limit. Spend the first 10 minutes on questions. They save the next 80.

A 90-minute plan

MinutesDo
0–10Clarify requirements and agree what's out of scope
10–20List entities and interfaces; sketch their relationships
20–70Write the code: model, inventory, allocation, entry and exit, fees
70–85Write tests, including the concurrency case
85–90Walk through an extension, such as electric-vehicle spots

Questions to ask

Entities and interfaces

enum VehicleType { MOTORCYCLE, CAR, TRUCK }
enum SpotSize { SMALL, MEDIUM, LARGE }

record Vehicle(String plate, VehicleType type) {}
record Spot(String id, int floor, SpotSize size) {}
record Ticket(String id, Vehicle vehicle, Spot spot, Instant entry) {}

interface SpotAllocationStrategy { Optional<Spot> claim(Vehicle vehicle, SpotInventory inventory); }
interface FeePolicy { long feeCents(Ticket ticket, Instant exit); }

Two interfaces carry the design. SpotAllocationStrategy decides which spot a vehicle gets, and FeePolicy decides what it pays. Both change often, and both are strategies, so adding "nearest to the lift" allocation or weekend pricing is a new class, not an edit.

Two cars, one spot

If two gates read "spot 17 is free" and then both mark it taken, two cars get the same spot. The fix is to make finding and claiming a spot one atomic step. Keep a concurrent queue of free spots per size: poll() removes and returns one element atomically, so two threads can never receive the same spot.

final class SpotInventory {
    private final Map<SpotSize, Queue<Spot>> free = new EnumMap<>(SpotSize.class);

    SpotInventory(Collection<Spot> spots) {
        for (SpotSize size : SpotSize.values()) free.put(size, new ConcurrentLinkedQueue<>());
        spots.forEach(this::release);
    }

    /** Atomically takes a free spot of this size. Two callers can never get the same spot. */
    Optional<Spot> claim(SpotSize size) { return Optional.ofNullable(free.get(size).poll()); }

    void release(Spot spot) { free.get(spot.size()).offer(spot); }
}

Allocation, fees and the lot

final class SmallestFit implements SpotAllocationStrategy {
    public Optional<Spot> claim(Vehicle vehicle, SpotInventory inventory) {
        for (SpotSize size : sizesThatFit(vehicle.type())) {
            Optional<Spot> spot = inventory.claim(size);
            if (spot.isPresent()) return spot;
        }
        return Optional.empty();
    }

    private static List<SpotSize> sizesThatFit(VehicleType type) {
        return switch (type) {
            case MOTORCYCLE -> List.of(SpotSize.SMALL, SpotSize.MEDIUM, SpotSize.LARGE);
            case CAR        -> List.of(SpotSize.MEDIUM, SpotSize.LARGE);
            case TRUCK      -> List.of(SpotSize.LARGE);
        };
    }
}

record HourlyFee(Map<SpotSize, Long> centsPerHour) implements FeePolicy {
    public long feeCents(Ticket ticket, Instant exit) {
        long minutes = Duration.between(ticket.entry(), exit).toMinutes();
        long hours = Math.max(1, (minutes + 59) / 60);           // round up, minimum one hour
        return hours * centsPerHour.get(ticket.spot().size());
    }
}

final class ParkingLot {
    private final SpotInventory inventory;
    private final SpotAllocationStrategy allocation;
    private final FeePolicy fees;
    private final Clock clock;
    private final Map<String, Ticket> active = new ConcurrentHashMap<>();

    ParkingLot(SpotInventory inventory, SpotAllocationStrategy allocation, FeePolicy fees, Clock clock) {
        this.inventory = inventory; this.allocation = allocation; this.fees = fees; this.clock = clock;
    }

    Optional<Ticket> enter(Vehicle vehicle) {
        return allocation.claim(vehicle, inventory).map(spot -> {
            Ticket ticket = new Ticket(UUID.randomUUID().toString(), vehicle, spot, clock.instant());
            active.put(ticket.id(), ticket);
            return ticket;
        });
    }

    long exit(String ticketId) {
        Ticket ticket = active.remove(ticketId);                // remove() is atomic: a ticket exits once
        if (ticket == null) throw new IllegalArgumentException("Unknown or already used ticket " + ticketId);
        inventory.release(ticket.spot());
        return fees.feeCents(ticket, clock.instant());
    }
}

Things worth pointing out as you write it:

If the state lives in a database

With several servers, the in-memory queue becomes a table, and the atomic claim becomes one SQL statement. FOR UPDATE SKIP LOCKED lets concurrent transactions each grab a different free row rather than queueing on the same one:

-- Claim one free medium spot; concurrent transactions skip rows already locked by others.
UPDATE spots SET occupied = true, ticket_id = :ticket
WHERE id = (
    SELECT id FROM spots
    WHERE size = 'MEDIUM' AND NOT occupied
    ORDER BY floor, id
    LIMIT 1
    FOR UPDATE SKIP LOCKED
)
RETURNING id;          -- no row returned means the lot is full

The extension point

Interviewers often end with "now add electric-vehicle charging spots". With this design that means: add EV to the size enum (or a separate feature flag on Spot), an allocation strategy that prefers EV spots for EVs, and perhaps a fee policy that adds charging. Nothing in ParkingLot changes. Say that out loud. It's the point of the exercise.

Interview checklist

Practise it

Exercise

Set a 90-minute timer and build it with no reference material: entities, allocation strategy, fee policy, and a test where 50 threads race for 10 spots. Then add an electric-vehicle spot type and count how many existing classes you had to edit.

Workshop drill

Do it by hand

Interactive drills for the parts the simulator can't show. Scored, with your best result saved in your browser.

Last spot race

Further reading