Skip to lesson

LLD: parking lot system

A mall gate sends cars, bikes and trucks to a spot that fits, hands out tickets and charges by the hour, while two gates work at the same time. It is the most common LLD question and small enough for 45 minutes.

Requirements: levels, spots, vehicles, tickets and fees

A fit table says which vehicle types can park in which spot sizes. Agree it first: it decides your canFit logic and is the first thing the interviewer changes.

Before drawing any class, settle the requirements. This is the list we will design for.

Text
Levels:     2 to start, each with a list of spotsSpot sizes: SMALL, MEDIUM, LARGEVehicles:   BIKE fits any spot; CAR fits MEDIUM or LARGE; TRUCK fits LARGE onlyEntry:      vehicle gets the smallest free spot that fits and a ticketTicket:     id, vehicle, spot, entry timeExit:       fee per started hour (minimum 1 hour), spot becomes freeRates:      BIKE Rs 20, CAR Rs 40, TRUCK Rs 100 per hourGates:      2 entry gates work at the same timeOut:        payments, reservations, display boards

Ask how many levels, which spot sizes, which vehicle types fit where, what a ticket holds and how the fee is worked out. Agree the fit table early; the first change an interviewer makes is usually "now add electric cars".

Also ask whether several entry gates work at the same time: if yes, two cars can reach for the same spot, and you need thread safety.

Entities: ParkingLot, Level, Spot, Vehicle, Ticket

A Spot is one parking place. It knows its size, whether it is free and whether a given vehicle fits, so the fit rule lives in one place.

The example writes Spot with the fit rule next to the spot sizes, then tries a bike, a car and a truck.

Example 1 · Spot sizes and the fit rule

FitRuleDemo.javaJava
enum VehicleType { BIKE, CAR, TRUCK }
enum SpotSize { SMALL, MEDIUM, LARGE }
record Vehicle(String number, VehicleType type) { }
class Spot {    private final String id;    private final SpotSize size;    private Vehicle parked;
    Spot(String id, SpotSize size) {        this.id = id;        this.size = size;    }
    static boolean fits(SpotSize size, VehicleType type) {        return switch (type) {            case BIKE -> true;            case CAR -> size != SpotSize.SMALL;            case TRUCK -> size == SpotSize.LARGE;        };    }
    boolean canFit(Vehicle vehicle) {        return parked == null && fits(size, vehicle.type());    }
    void park(Vehicle vehicle) { parked = vehicle; }    String id() { return id; }}
public class FitRuleDemo {    public static void main(String[] args) {        for (VehicleType type : VehicleType.values()) {            StringBuilder line = new StringBuilder(type + " fits:");            for (SpotSize size : SpotSize.values()) {                if (Spot.fits(size, type)) line.append(" ").append(size);            }            System.out.println(line);        }
        Spot m1 = new Spot("M1", SpotSize.MEDIUM);        Vehicle car = new Vehicle("KA01AB1234", VehicleType.CAR);        System.out.println("M1 free for car? " + m1.canFit(car));        m1.park(car);        System.out.println("M1 free for another car? " + m1.canFit(new Vehicle("KA05CD9876", VehicleType.CAR)));    }}
Output
BIKE fits: SMALL MEDIUM LARGE
CAR fits: MEDIUM LARGE
TRUCK fits: LARGE
M1 free for car? true
M1 free for another car? false

What this code does

  • The whole fit table lives in one switch next to the enums. A new vehicle type is one new case, and the compiler reminds you if you forget it.
  • canFit combines two checks: the spot is free and the size suits the vehicle type.
  • Once a car is parked, canFit is false for everyone, which is the rule the thread-safety section must protect.

Vehicle is a small value (number plate and type), so a record fits. Ticket records who parked where and when, Level holds a list of spots, and ParkingLot holds the levels and the active tickets.

Keep the fit rule in one place, next to the spot sizes, so a new vehicle type changes one method and not five.

Predict the output

Predict the fit rule

The fit table: BIKE fits any spot, CAR fits MEDIUM or LARGE, TRUCK fits LARGE only.

Round 1 of 2

Spot m1 = new Spot("M1", SpotSize.MEDIUM);
Vehicle truck = new Vehicle("KA01TR3333", VehicleType.TRUCK);
System.out.println(m1.canFit(truck));

Spot assignment strategy and fee strategy

A spot assignment strategy is the rule that picks a spot for an arriving vehicle, such as the first free spot or the smallest spot that fits.

Two examples: two ways to pick a spot, then a fee rule that charges per started hour.

Example 2 · Two spot assignment strategies

AssignmentDemo.javaJava
import java.util.Comparator;import java.util.List;import java.util.Optional;
enum SpotSize { SMALL, MEDIUM, LARGE }
record Spot(String id, SpotSize size, boolean free) { }
interface SpotAssignmentStrategy {    Optional<Spot> choose(List<Spot> spots, SpotSize smallestNeeded);}
class FirstFree implements SpotAssignmentStrategy {    public Optional<Spot> choose(List<Spot> spots, SpotSize smallestNeeded) {        return spots.stream()                .filter(s -> s.free() && s.size().compareTo(smallestNeeded) >= 0)                .findFirst();    }}
class SmallestFit implements SpotAssignmentStrategy {    public Optional<Spot> choose(List<Spot> spots, SpotSize smallestNeeded) {        return spots.stream()                .filter(s -> s.free() && s.size().compareTo(smallestNeeded) >= 0)                .min(Comparator.comparing(Spot::size));    }}
public class AssignmentDemo {    public static void main(String[] args) {        List<Spot> spots = List.of(                new Spot("L1", SpotSize.LARGE, true),                new Spot("M1", SpotSize.MEDIUM, false),                new Spot("S1", SpotSize.SMALL, true),                new Spot("M2", SpotSize.MEDIUM, true));
        List<SpotAssignmentStrategy> strategies = List.of(new FirstFree(), new SmallestFit());        for (SpotAssignmentStrategy strategy : strategies) {            String name = strategy.getClass().getSimpleName();            System.out.println(name + " for a bike: " + strategy.choose(spots, SpotSize.SMALL).map(Spot::id).orElse("none"));            System.out.println(name + " for a car:  " + strategy.choose(spots, SpotSize.MEDIUM).map(Spot::id).orElse("none"));        }    }}
Output
FirstFree for a bike: L1
FirstFree for a car:  L1
SmallestFit for a bike: S1
SmallestFit for a car:  M2

What this code does

  • Both classes answer the same question through one interface, so the lot can use either without knowing which.
  • FirstFree wastes the large spot L1 on a bike. SmallestFit keeps large spots for trucks by choosing the smallest size that is big enough.
  • Enum constants compare in declaration order, so compareTo(smallestNeeded) >= 0 means "this size or bigger".

Example 3 · Fee strategy: per started hour

FeeDemo.javaJava
import java.time.Duration;import java.util.Map;
enum VehicleType { BIKE, CAR, TRUCK }
interface FeeStrategy {    int fee(VehicleType type, Duration parked);}
class HourlyFee implements FeeStrategy {    private final Map<VehicleType, Integer> ratePerHour =            Map.of(VehicleType.BIKE, 20, VehicleType.CAR, 40, VehicleType.TRUCK, 100);
    public int fee(VehicleType type, Duration parked) {        long minutes = parked.toMinutes();        long hours = Math.max(1, (minutes + 59) / 60);   // every started hour counts        return (int) hours * ratePerHour.get(type);    }}
public class FeeDemo {    public static void main(String[] args) {        FeeStrategy fees = new HourlyFee();        int[] stays = {10, 60, 61, 150};        for (int minutes : stays) {            Duration d = Duration.ofMinutes(minutes);            System.out.println(minutes + " min: car Rs " + fees.fee(VehicleType.CAR, d)                    + ", bike Rs " + fees.fee(VehicleType.BIKE, d));        }    }}
Output
10 min: car Rs 40, bike Rs 20
60 min: car Rs 40, bike Rs 20
61 min: car Rs 80, bike Rs 40
150 min: car Rs 120, bike Rs 60

What this code does

  • (minutes + 59) / 60 is integer division that rounds up, so 61 minutes is 2 started hours.
  • Math.max(1, ...) makes the minimum charge one hour, even for a 10-minute stop.
  • Rates sit in one map inside the strategy. A weekend tariff would be another FeeStrategy, not a change here.

A fee strategy is the rule that turns parked time into rupees. Both rules are classic places for the Strategy pattern, because the business changes them often (nearest to the lift, weekend flat rate) while the rest of the lot stays the same.

Put each rule behind an interface and pass the chosen one into ParkingLot. Then "a flat Rs 100 on Sundays" is a new class, not an edit to the lot.

Thread safety when two cars take the same spot

A race condition happens when two threads read and change the same data at the same time and the result depends on timing.

Two gates, one free spot: the unsafe version lets both cars in, the safe version does not.

Java
// Unsafe: two gates can both pass the check before either one parksSpot spot = findFreeSpot(vehicle);   // checkspot.park(vehicle);                  // act
// Safe: the check and the act run as one step under the lot's locksynchronized Optional<Ticket> park(Vehicle vehicle, LocalDateTime at) {    Optional<Spot> spot = assignment.find(levels, vehicle);    spot.ifPresent(s -> s.park(vehicle));    ...}
Two gates, one free spot M1. Gate A checks: free. Gate B checks: also free. Gate A parks in M1. Gate B parks in M1 too, so one spot holds two cars. With a synchronized park, gate B waits and then sees M1 taken.

Example 4 · Fifty cars, ten spots, no double booking

SafeParkingDemo.javaJava
import java.util.Set;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;
class SpotBoard {    private final boolean[] taken;
    SpotBoard(int spots) { taken = new boolean[spots]; }
    // check and act in one locked step    synchronized int takeFirstFree() {        for (int i = 0; i < taken.length; i++) {            if (!taken[i]) {                taken[i] = true;                return i;            }        }        return -1;    }}
public class SafeParkingDemo {    public static void main(String[] args) throws InterruptedException {        SpotBoard board = new SpotBoard(10);        Set<Integer> givenOut = ConcurrentHashMap.newKeySet();        AtomicInteger tickets = new AtomicInteger();        AtomicInteger duplicates = new AtomicInteger();        AtomicInteger turnedAway = new AtomicInteger();
        ExecutorService gates = Executors.newFixedThreadPool(4);        for (int car = 0; car < 50; car++) {            gates.submit(() -> {                int spot = board.takeFirstFree();                if (spot < 0) {                    turnedAway.incrementAndGet();                } else {                    tickets.incrementAndGet();                    if (!givenOut.add(spot)) duplicates.incrementAndGet();                }            });        }        gates.shutdown();        gates.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("Tickets issued: " + tickets.get());        System.out.println("Turned away: " + turnedAway.get());        System.out.println("Spots given twice: " + duplicates.get());    }}
Output
Tickets issued: 10
Turned away: 40
Spots given twice: 0

What this code does

  • Four threads act as four gates, and fifty cars arrive at once. Because takeFirstFree is synchronized, only one gate at a time can check and take a spot.
  • Which car gets which spot changes from run to run, but the counts never do: exactly 10 tickets and no spot given twice.
  • Remove synchronized and run it a few times: on most machines Spots given twice sooner or later becomes more than 0.

In a lot with two gates, both gates can find spot M1 free, and both then park in it. This is a check-then-act bug: the check (isFree) and the act (park) are two steps another thread can slip between.

The fix is to make "find a free spot and take it" one step that only one thread runs at a time. A synchronized method does that: a thread must hold the lot's lock to enter, so the second gate waits and then sees M1 already taken.

Order of execution

How two gates book one spot

Put the steps in the order that gives the double booking.

One lock for the whole lot is simple and correct. A very busy lot could lock per level instead; say that as a follow-up, not as the first design.

Single-file design with a demo run

An extension point is a place where a new requirement plugs in without rewriting existing code, such as a new FeeStrategy class.

The whole lot in one file, with fixed times in the demo so the output is the same on every run.

Example 5 · The whole parking lot in one file

ParkingLotDemo.javaJava
import java.time.Duration;import java.time.LocalDateTime;import java.util.Comparator;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Optional;
enum VehicleType { BIKE, CAR, TRUCK }enum SpotSize { SMALL, MEDIUM, LARGE }
record Vehicle(String number, VehicleType type) { }
class Spot {    final String id;    final SpotSize size;    private Vehicle parked;    Spot(String id, SpotSize size) { this.id = id; this.size = size; }    boolean canFit(Vehicle v) { return parked == null && fits(size, v.type()); }    static boolean fits(SpotSize size, VehicleType type) {        return switch (type) {            case BIKE -> true;            case CAR -> size != SpotSize.SMALL;            case TRUCK -> size == SpotSize.LARGE;        };    }    void park(Vehicle v) { parked = v; }    void free() { parked = null; }}
record Level(int number, List<Spot> spots) { }
record Ticket(String id, Vehicle vehicle, Spot spot, LocalDateTime entry) { }
interface SpotAssignmentStrategy { Optional<Spot> find(List<Level> levels, Vehicle v); }
class SmallestFit implements SpotAssignmentStrategy {    public Optional<Spot> find(List<Level> levels, Vehicle v) {        return levels.stream().flatMap(l -> l.spots().stream())                .filter(s -> s.canFit(v))                .min(Comparator.comparing((Spot s) -> s.size));    }}
interface FeeStrategy { int fee(VehicleType type, Duration parked); }
class HourlyFee implements FeeStrategy {    private final Map<VehicleType, Integer> rate = Map.of(VehicleType.BIKE, 20, VehicleType.CAR, 40, VehicleType.TRUCK, 100);    public int fee(VehicleType type, Duration parked) {        long hours = Math.max(1, (parked.toMinutes() + 59) / 60);        return (int) hours * rate.get(type);    }}
class ParkingLot {    private final List<Level> levels;    private final SpotAssignmentStrategy assignment;    private final FeeStrategy fees;    private final Map<String, Ticket> active = new HashMap<>();    private int nextTicket = 1;
    ParkingLot(List<Level> levels, SpotAssignmentStrategy assignment, FeeStrategy fees) {        this.levels = levels;        this.assignment = assignment;        this.fees = fees;    }
    synchronized Optional<Ticket> park(Vehicle v, LocalDateTime at) {        Optional<Spot> spot = assignment.find(levels, v);        if (spot.isEmpty()) return Optional.empty();        spot.get().park(v);        Ticket ticket = new Ticket("T" + nextTicket++, v, spot.get(), at);        active.put(ticket.id(), ticket);        return Optional.of(ticket);    }
    synchronized int unpark(String ticketId, LocalDateTime at) {        Ticket ticket = active.remove(ticketId);        if (ticket == null) throw new IllegalArgumentException("Unknown ticket " + ticketId);        ticket.spot().free();        return fees.fee(ticket.vehicle().type(), Duration.between(ticket.entry(), at));    }}
public class ParkingLotDemo {    static void enter(ParkingLot lot, Vehicle v, LocalDateTime at) {        String result = lot.park(v, at).map(t -> t.id() + " at spot " + t.spot().id).orElse("lot full for " + v.type());        System.out.println(v.number() + " (" + v.type() + "): " + result);    }
    public static void main(String[] args) {        Level ground = new Level(0, List.of(new Spot("S1", SpotSize.SMALL), new Spot("M1", SpotSize.MEDIUM)));        Level first = new Level(1, List.of(new Spot("M2", SpotSize.MEDIUM), new Spot("L1", SpotSize.LARGE)));        ParkingLot lot = new ParkingLot(List.of(ground, first), new SmallestFit(), new HourlyFee());        LocalDateTime nine = LocalDateTime.of(2026, 10, 16, 9, 0);
        enter(lot, new Vehicle("KA01BK1111", VehicleType.BIKE), nine);        enter(lot, new Vehicle("KA01CR2222", VehicleType.CAR), nine);        enter(lot, new Vehicle("KA01TR3333", VehicleType.TRUCK), nine);        enter(lot, new Vehicle("KA01CR4444", VehicleType.CAR), nine);        enter(lot, new Vehicle("KA01CR5555", VehicleType.CAR), nine);
        System.out.println("T2 leaves after 2h 10m, pays Rs " + lot.unpark("T2", nine.plusMinutes(130)));        enter(lot, new Vehicle("KA01CR5555", VehicleType.CAR), nine.plusMinutes(135));    }}
Output
KA01BK1111 (BIKE): T1 at spot S1
KA01CR2222 (CAR): T2 at spot M1
KA01TR3333 (TRUCK): T3 at spot L1
KA01CR4444 (CAR): T4 at spot M2
KA01CR5555 (CAR): lot full for CAR
T2 leaves after 2h 10m, pays Rs 120
KA01CR5555 (CAR): T5 at spot M1

What this code does

  • ParkingLot receives its two strategies in the constructor, so the demo could pass FirstFree or a weekend fee without touching the lot.
  • park and unpark are synchronized, so the find-and-take step from the previous example is safe here too.
  • The fifth car finds no MEDIUM or LARGE spot and is turned away; after T2 leaves, it gets M1. Fixed times make the fee (3 started hours × Rs 40) the same every run.

The single-file design puts every class in one Java file: helper types without public, and one public demo class. After the demo works, talk through the extension points:

  • New vehicle type (electric car): one enum value and one line in the fit rule; strategies stay the same.
  • New pricing (weekend flat rate): a new FeeStrategy class passed to the lot.
  • New spot choice (nearest to lift): a new SpotAssignmentStrategy class.
  • Display board of free spots: a method that counts free spots per size; later an observer on park and unpark.

Next step

Check your understanding

12 quick questions