LOW LEVEL DESIGN · MACHINE CODING · EASY · 1 OF 42

Design a Parking Lot: Low-Level Design with Java Code

The most common machine coding question, solved end to end: requirements, the entities, a class diagram, spot fitting rules, Strategy for spot choice and pricing, Observer for display boards, the entry and exit flows, two gates racing for one spot (compare-and-set), tickets used once, extension points and the follow-ups, with a full Java 17 solution.

Patterns usedObserverStrategyDecorator

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 18

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 217 lines, with a small main() demo. Save it as ParkingLot.java, then run javac ParkingLot.java && java ParkingLot.

import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;

/** A multi-floor parking lot: gates issue tickets, spots are claimed atomically, fees use a strategy. */
public class ParkingLot {

    // ---------- the model ----------
    enum VehicleType { MOTORCYCLE, CAR, TRUCK }

    enum SpotSize { SMALL, MEDIUM, LARGE }

    record Vehicle(String plate, VehicleType type) {}

    static final class Spot {
        final String id;
        final int floor;
        final SpotSize size;
        private final AtomicReference<Vehicle> parked = new AtomicReference<>();

        Spot(String id, int floor, SpotSize size) {
            this.id = id;
            this.floor = floor;
            this.size = size;
        }

        boolean fits(Vehicle v) {
            return switch (v.type()) {
                case MOTORCYCLE -> true;
                case CAR -> size != SpotSize.SMALL;
                case TRUCK -> size == SpotSize.LARGE;
            };
        }

        /** Compare-and-set: two gates can never park in the same spot. */
        boolean tryPark(Vehicle v) { return parked.compareAndSet(null, v); }

        void release() { parked.set(null); }

        boolean isFree() { return parked.get() == null; }
    }

    record Floor(int number, List<Spot> spots) {}

    record Ticket(String id, Vehicle vehicle, Spot spot, Instant entry) {}

    record Receipt(String ticketId, String plate, Duration stayed, long feeCents) {}

    // ---------- strategies and observers ----------
    /** Which spots to try, in order. Swap it for "nearest the lift", "EV first", and so on. */
    interface SpotStrategy { List<Spot> candidates(List<Floor> floors, Vehicle v); }

    /** Best fit: the smallest size that fits, lowest floor first, so big spots stay free for big vehicles. */
    static final class BestFitStrategy implements SpotStrategy {
        public List<Spot> candidates(List<Floor> floors, Vehicle v) {
            List<Spot> out = new ArrayList<>();
            for (SpotSize size : SpotSize.values())
                for (Floor f : floors)
                    for (Spot s : f.spots())
                        if (s.size == size && s.isFree() && s.fits(v)) out.add(s);
            return out;
        }
    }

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

    /** Charge per started hour, with a different hourly rate per spot size. */
    static final class HourlyPricing implements PricingStrategy {
        private final Map<SpotSize, Long> centsPerHour;

        HourlyPricing(Map<SpotSize, Long> centsPerHour) { this.centsPerHour = centsPerHour; }

        public long feeCents(Ticket t, Instant exit) {
            long minutes = Math.max(1, Duration.between(t.entry(), exit).toMinutes());
            long hours = (minutes + 59) / 60;
            return hours * centsPerHour.get(t.spot().size);
        }
    }

    interface PaymentMethod { boolean charge(long cents); }

    /** Display boards at the gates subscribe to free-spot counts. */
    interface AvailabilityListener { void onChange(SpotSize size, long free); }

    // ---------- the lot ----------
    private final List<Floor> floors;
    private final SpotStrategy spotStrategy;
    private final PricingStrategy pricing;
    private final Supplier<Instant> clock;
    private final Map<String, Ticket> active = new ConcurrentHashMap<>();
    private final Map<String, String> ticketByPlate = new ConcurrentHashMap<>();
    private final List<AvailabilityListener> listeners = new CopyOnWriteArrayList<>();
    private final AtomicLong ticketSeq = new AtomicLong();

    ParkingLot(List<Floor> floors, SpotStrategy spots, PricingStrategy pricing, Supplier<Instant> clock) {
        this.floors = List.copyOf(floors);
        this.spotStrategy = spots;
        this.pricing = pricing;
        this.clock = clock;
    }

    void subscribe(AvailabilityListener l) { listeners.add(l); }

    /** Entry gate: find a spot, claim it atomically, issue a ticket. */
    Ticket enter(Vehicle v) {
        if (ticketByPlate.putIfAbsent(v.plate(), "pending") != null)
            throw new IllegalStateException(v.plate() + " is already inside");
        for (Spot s : spotStrategy.candidates(floors, v)) {
            if (!s.tryPark(v)) continue; // another gate won this spot; try the next one
            Ticket t = new Ticket("T" + ticketSeq.incrementAndGet(), v, s, clock.get());
            active.put(t.id(), t);
            ticketByPlate.put(v.plate(), t.id());
            publish(s.size);
            return t;
        }
        ticketByPlate.remove(v.plate());
        throw new IllegalStateException("No free spot for a " + v.type());
    }

    /** Exit gate: price the stay, take payment, then free the spot. */
    Receipt exit(String ticketId, PaymentMethod payment) {
        Ticket t = active.remove(ticketId); // remove first: a ticket can be used only once
        if (t == null) throw new IllegalArgumentException("Unknown or used ticket " + ticketId);
        Instant now = clock.get();
        long fee = pricing.feeCents(t, now);
        if (!payment.charge(fee)) {
            active.put(ticketId, t); // declined: the car is still inside
            throw new IllegalStateException("Payment declined");
        }
        ticketByPlate.remove(t.vehicle().plate());
        t.spot().release();
        publish(t.spot().size);
        return new Receipt(t.id(), t.vehicle().plate(), Duration.between(t.entry(), now), fee);
    }

    long freeSpots(SpotSize size) {
        return floors.stream().flatMap(f -> f.spots().stream())
                .filter(s -> s.size == size && s.isFree()).count();
    }

    private void publish(SpotSize size) {
        long free = freeSpots(size);
        for (AvailabilityListener l : listeners) l.onChange(size, free);
    }

    // ---------- demo ----------
    static Floor floor(int n, int small, int medium, int large) {
        List<Spot> spots = new ArrayList<>();
        int k = 0;
        for (int i = 0; i < small; i++) spots.add(new Spot(n + "-S" + (++k), n, SpotSize.SMALL));
        for (int i = 0; i < medium; i++) spots.add(new Spot(n + "-M" + (++k), n, SpotSize.MEDIUM));
        for (int i = 0; i < large; i++) spots.add(new Spot(n + "-L" + (++k), n, SpotSize.LARGE));
        return new Floor(n, spots);
    }

    public static void main(String[] args) throws InterruptedException {
        AtomicReference<Instant> now = new AtomicReference<>(Instant.parse("2026-01-01T09:00:00Z"));
        Map<SpotSize, Long> rates = new EnumMap<>(SpotSize.class);
        rates.put(SpotSize.SMALL, 100L);
        rates.put(SpotSize.MEDIUM, 200L);
        rates.put(SpotSize.LARGE, 400L);
        ParkingLot lot = new ParkingLot(List.of(floor(1, 1, 2, 1), floor(2, 1, 2, 0)),
                new BestFitStrategy(), new HourlyPricing(rates), now::get);
        lot.subscribe((size, free) -> System.out.println("  [board] " + size + " free: " + free));

        Ticket car = lot.enter(new Vehicle("KA01AB1234", VehicleType.CAR));
        Ticket bike = lot.enter(new Vehicle("KA02XY9", VehicleType.MOTORCYCLE));
        Ticket truck = lot.enter(new Vehicle("KA03TR77", VehicleType.TRUCK));
        System.out.println(car.vehicle().plate() + " -> " + car.spot().id);
        System.out.println(bike.vehicle().plate() + " -> " + bike.spot().id);
        System.out.println(truck.vehicle().plate() + " -> " + truck.spot().id);

        now.set(now.get().plus(Duration.ofMinutes(150)));
        Receipt r = lot.exit(car.id(), cents -> true);
        System.out.printf("Receipt: %s stayed %d min, paid %.2f%n", r.plate(), r.stayed().toMinutes(),
                r.feeCents() / 100.0);

        // Eight gates race for the medium spots: each spot is taken exactly once.
        int mediumFree = (int) lot.freeSpots(SpotSize.MEDIUM);
        AtomicInteger parked = new AtomicInteger(), turnedAway = new AtomicInteger();
        CountDownLatch start = new CountDownLatch(1);
        ExecutorService gates = Executors.newFixedThreadPool(8);
        for (int i = 0; i < 8; i++) {
            String plate = "RACE" + i;
            gates.submit(() -> {
                try {
                    start.await();
                    lot.enter(new Vehicle(plate, VehicleType.CAR));
                    parked.incrementAndGet();
                } catch (IllegalStateException e) {
                    turnedAway.incrementAndGet();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        start.countDown();
        gates.shutdown();
        gates.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("Race: " + mediumFree + " medium free, " + parked.get() + " parked, "
                + turnedAway.get() + " turned away");
        if (parked.get() != mediumFree) throw new AssertionError("double parking");
    }
}

Notes

Requirements

Start by fixing the scope. The lot has several floors with small, medium and large spots. Motorcycles, cars and trucks arrive. The entry gate finds a spot and issues a ticket, the exit gate charges by the hour, and payment can be card, cash or UPI. Display boards show free spots per size. Several gates work at the same time. Say what is out of scope, like reservations, so the interviewer can push back early.

Ask the questions that change the code. Can a motorcycle use a car spot? Yes, smaller vehicles fit bigger spots. Can a truck span two spots? No, it needs a large one. Is pricing flat or hourly? Hourly, with a rate per spot size. What about a lost ticket? Charge a daily maximum. Each answer becomes a rule in a specific class, which is exactly what the interviewer wants to see.

Requirements
  • several floors, many spots
  • spot sizes: small, medium, large
  • vehicles: bike, car, truck
  • entry gate issues a ticket
  • exit gate charges by the hour
  • pay by card, cash or UPI
  • boards show free spots per size
  • many gates work at once
  • out of scope: booking ahead,
  • number plate cameras
Clarify first
  • can a bike use a car spot?
  • yes: smaller fits bigger
  • can a truck use two spots?
  • no: trucks need large
  • flat fee or hourly?
  • hourly, rate per spot size
  • lost ticket?
  • charge the daily maximum
  • one lot or many?
  • one lot, many gates

Entities

Now the entities. Underline the nouns in the requirements: lot, floor, spot, vehicle, ticket. The lot has many floors, each floor has many spots, and a spot holds at most one vehicle. The lot issues a ticket that points at the vehicle, the spot and the entry time. Notice what is not a class: a gate is just a caller of the lot, so we keep it out of the model until it needs its own behaviour.

Class diagram

Turn them into types. Fixed kinds become enums: vehicle type and spot size. Things that never change after creation become Java records: a vehicle, a floor, a ticket, a receipt. Money is a long number of cents, never a double, so rounding never loses a paisa. Only one class has changing state, the spot, because it is either free or holding a vehicle. Keeping mutable state in one place makes the thread safety story short.

Where does the rule live that a car cannot use a small spot? On the spot, because the spot owns its size. A switch over the vehicle type returns true or false, and the compiler checks every enum value is covered, so adding a new vehicle type later forces you to decide its rule. Put behaviour next to the data it reads; that one habit answers most where-does-this-go questions.

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

record Vehicle(String plate, VehicleType t)
record Floor(int number, List<Spot> spots)
record Ticket(String id, Vehicle vehicle,
              Spot spot, Instant entry)
record Receipt(id, plate, stayed, fee)
Spot.fits()
boolean fits(Vehicle v) {
  return switch (v.type()) {
    case MOTORCYCLE -> true;
    case CAR -> size != SpotSize.SMALL;
    case TRUCK -> size == SpotSize.LARGE;
  };
}

Strategy: spot choice

Which spot should a car get? That is a business policy, and policies change, so put it behind an interface: the Strategy pattern. Our default is best fit: try the smallest size that fits, lowest floor first, so large spots stay free for trucks. Tomorrow the business wants nearest to the lift, or electric charging spots first. Each is a new class, and the parking lot itself does not change. That is the open-closed principle in one sentence.

SpotStrategy
interface SpotStrategy {
  List<Spot> candidates(List<Floor> f,
                        Vehicle v);
}

BestFitStrategy: smallest size that
  fits, lowest floor first
NearestLiftStrategy, EvFirstStrategy:
  new classes, ParkingLot unchanged

Strategy: pricing

Pricing is the second strategy. HourlyPricing charges per started hour with a rate per spot size, so a hundred and fifty minutes on a medium spot is three hours. A weekend rate or a flat event fee is another class. Payment is a third tiny interface with one method, charge, so card, cash and UPI plug in without the lot knowing which is which. Three small interfaces beat one giant class full of if statements.

Pricing per started hour
long feeCents(Ticket t, Instant exit) {
  long min = max(1, between(entry, exit)
                      .toMinutes());
  long hours = (min + 59) / 60;
  return hours * centsPerHour.get(size);
}

150 minutes on a medium spot
= 3 hours x 200 = 600 cents

Observer: boards

Display boards use the Observer pattern. Each board subscribes with a listener, and after every park or release the lot publishes the new free count for that size. The lot does not care whether one board or fifty are listening, or whether one of them is a mobile app or a metrics exporter. The listener list is a copy-on-write list, so a board can subscribe while gates are busy without any locking.

Observer
interface AvailabilityListener {
  void onChange(SpotSize s, long free);
}
listeners = new CopyOnWriteArrayList

after every park or release:
  for (l : listeners) l.onChange(..)

boards, a mobile app, metrics:
  all just subscribe

Flow: entry

Walk the entry flow. First reject a plate that is already inside. Ask the strategy for candidate spots in order. Try to claim each one; if another gate got it first, move to the next. Once a spot is ours, create the ticket with the time from an injected clock, store it in a map of active tickets, and tell the boards. If no candidate works, throw a clear lot-full error for that vehicle type.

enter(vehicle)
reject if plate already inside
for (Spot s : strategy.candidates(..)) {
  if (!s.tryPark(v)) continue;
  Ticket t = new Ticket(nextId(), v, s,
                        clock.get());
  active.put(t.id(), t);
  publish(s.size);
  return t;
}
throw: no free spot for this type

Flow: exit

The exit flow. Remove the ticket from the active map first: that single atomic step means a ticket can only ever be used once, even if two exits race. Price the stay, charge the payment method, and if the payment is declined, put the ticket back because the car is still inside. Only after a successful charge do we release the spot, notify the boards and return a receipt.

exit(ticketId, payment)
t = active.remove(ticketId)
if (t == null) throw: used or unknown
fee = pricing.feeCents(t, now)
if (!payment.charge(fee)) {
  active.put(ticketId, t)  // put back
  throw: payment declined
}
t.spot().release()
publish(size); return receipt

Concurrency

Now the part that separates good answers from great ones: concurrency. Two gates both see spot one-M-two as free at the same instant. If parking were check-then-set, both would win and two cars would share a spot. Instead each spot holds an atomic reference, and parking is a compare-and-set from empty to this vehicle. Exactly one gate succeeds; the loser simply tries its next candidate. No global lock, so gates never wait on each other.

Go through every shared field and give it a safe home. Spot state is atomic. Active tickets live in a concurrent hash map. A plate is reserved with put-if-absent, so the same car cannot enter twice through two gates. Ticket numbers come from an atomic counter. Listeners sit in a copy-on-write list. And everything else is an immutable record, which is safe to share without any locking at all.

No double parking
AtomicReference<Vehicle> parked

boolean tryPark(Vehicle v) {
  return parked.compareAndSet(null, v);
}

gate 1 and gate 2 both see 1-M2 free
gate 1: null to car A, true
gate 2: expected null, false
  so it tries the next candidate
Thread safety checklist
  • spot state: AtomicReference
  • active tickets: ConcurrentHashMap
  • plate already inside:
  • putIfAbsent on plate map
  • ticket ids: AtomicLong
  • listeners: CopyOnWriteArrayList
  • ticket used once:
  • remove() before charging
  • records are immutable:
  • safe to share freely

Extensibility

Interviewers love to change the requirements halfway. Electric charging spots? Add a feature to the spot and an EV-first strategy. Reservations? A reservation object that holds a spot until a time. Monthly passes? A pricing decorator that returns zero for pass holders and delegates otherwise. A new vehicle type? The switch forces you to decide where it fits. Each change is a new class rather than a risky edit.

Extension points
  • EV spots: new SpotSize or a
  • feature flag + EvFirstStrategy
  • reservations: a Reservation
  • holds a spot until a time
  • monthly passes: a Pricing
  • decorator that returns 0
  • new vehicle type: compiler
  • forces a fits() decision
  • many lots: a LotRegistry
  • keyed by lot id

Testing

The full code is below the player. The demo parks a car, a bike and a truck, moves a fake clock forward two and a half hours and checks the fee, then starts eight threads that race for four medium spots. Exactly four park and four are turned away, every time. Injecting the clock as a supplier is what makes the pricing testable without sleeping, so mention it.

Run it
KA01AB1234 -> 1-M2
KA02XY9 -> 1-S1
KA03TR77 -> 1-L4
Receipt: KA01AB1234 stayed 150 min,
         paid 6.00
Race: 4 medium free, 4 parked,
      4 turned away

clock is a Supplier<Instant>, so the
test moves time without sleeping

Follow-ups

Expect follow-ups. Why not one synchronized method? It works, but every gate would queue behind every other gate, and compare-and-set avoids that. What if the process restarts? Tickets move to a database with the spot id as a unique key. Nearest spot to an exit? Keep a heap of free spots per size per exit. And which design principles did you use? Single responsibility for each class, and open-closed through the strategies.

Follow-ups to expect
  • why not one big synchronized?
  • what if the app server dies?
  • persist tickets in a DB
  • lost ticket: daily maximum
  • how do boards stay correct
  • after a crash? recount
  • nearest spot to the exit:
  • a heap per size per gate
  • which SOLID principles?
  • open-closed, single resp.

Say it like this

Here is the short version to say out loud. The lot has floors, floors have spots, and a spot holds at most one vehicle. Spot choice, pricing and payment are strategies, and display boards are observers. Parking is a compare-and-set on the spot, so two gates never share one. Tickets live in a concurrent map and are removed exactly once. New rules arrive as new classes, not edits.

In the interview
  • "Lot has floors, floors have
  • spots, a spot holds one vehicle.
  • Spot choice, pricing and
  • payment are strategies; boards
  • are observers. Parking is a
  • compare-and-set on the spot,
  • tickets live in a concurrent
  • map and are removed once.
  • New rules are new classes."

Interview questions

How do you stop two entry gates from assigning the same spot?

Make claiming a spot atomic. Each spot keeps an AtomicReference to the parked vehicle and parking is compareAndSet(null, vehicle); only one gate can succeed, and the loser moves on to the next candidate spot. No global lock is needed.

Why use the Strategy pattern for spot selection and pricing?

Both are business policies that change often: nearest to the lift, EV first, weekend rates, event pricing. Behind an interface each new rule is a new class, and ParkingLot does not change, which follows the open-closed principle.

Where does the rule "a car cannot park in a small spot" belong?

On Spot, the class that owns the size. A switch over the vehicle type keeps the rule in one place, and because the switch is exhaustive the compiler forces a decision whenever a new vehicle type is added.

How do the display boards stay up to date?

Observer pattern: boards register an AvailabilityListener, and after every park or release the lot publishes the new free count for that size. Listeners live in a CopyOnWriteArrayList so they can subscribe while gates are active.

How do you make sure a ticket can only be paid once?

Remove it from the concurrent map of active tickets before charging. Removal is atomic, so a second exit with the same ticket finds nothing. If the payment is declined, put the ticket back because the car is still inside.

Why store money as long cents instead of double?

Binary floating point cannot represent most decimal amounts exactly, so sums drift. Whole cents in a long are exact, and you format them as currency only for display.

How would you test the hourly pricing?

Inject the clock as a Supplier of Instant. The test sets the entry time, moves the fake clock forward by 150 minutes and asserts the fee for three started hours, with no sleeping and no flaky timing.

What changes if the lot must survive a server restart?

Persist tickets and spot assignments in a database, with the spot id unique among active tickets so the database also rejects double parking. On startup, rebuild the in-memory free lists and board counts from the active tickets.