AlgoViz

Design a parking lot

medium 90 min

Model a car park with several levels as classes: vehicles, spaces of different sizes, tickets and a replaceable price rule.

Watch lesson4:48

The whole parking lot

Read it, run it, change a line and run it again.

Loading editor…

The parts of the implementation page in one file. It prints M1 S1 L1 M2, then 600. Try a second bus, a declined card, or another price rule. The lock is there for real gates: a browser runs one thread.

The same in Java
import java.time.Duration;import java.time.Instant;import java.util.*;enum SpotSize { SMALL, MEDIUM, LARGE }enum VehicleType {    MOTORCYCLE(SpotSize.SMALL), CAR(SpotSize.MEDIUM), BUS(SpotSize.LARGE);    final SpotSize minSize;    VehicleType(SpotSize minSize) { this.minSize = minSize; }}record Vehicle(String plate, VehicleType type) {}record Spot(String id, int level, SpotSize size) {}record Ticket(long id, Vehicle vehicle, Spot spot, Instant enteredAt) {}record Receipt(Ticket ticket, Instant leftAt, long cents) {}class AlreadyInside extends RuntimeException {    AlreadyInside(String plate) { super(plate); }}class UnknownTicket extends RuntimeException {    UnknownTicket(long id) { super("ticket " + id); }}class PaymentDeclined extends RuntimeException {    PaymentDeclined(String key) { super(key); }}/** The free spaces, one queue per size. The caller holds the lot's lock. */final class SpotPool {    private final Map<SpotSize, Deque<Spot>> free = new EnumMap<>(SpotSize.class);    SpotPool(List<Spot> spots) {        for (SpotSize size : SpotSize.values()) free.put(size, new ArrayDeque<>());        for (Spot spot : spots) free.get(spot.size()).addLast(spot);    }    Optional<Spot> claim(SpotSize smallest) {        for (SpotSize size : SpotSize.values()) {            if (size.compareTo(smallest) < 0) continue;            Spot spot = free.get(size).pollFirst();            if (spot != null) return Optional.of(spot);        }        return Optional.empty();    }    void release(Spot spot) { free.get(spot.size()).addFirst(spot); }    Map<SpotSize, Integer> counts() {        Map<SpotSize, Integer> out = new EnumMap<>(SpotSize.class);        free.forEach((size, queue) -> out.put(size, queue.size()));        return out;    }}interface Pricing { long priceCents(Ticket ticket, Instant leftAt); }final class HourlyPricing implements Pricing {    private final Map<SpotSize, Long> centsPerHour;    HourlyPricing(Map<SpotSize, Long> centsPerHour) { this.centsPerHour = centsPerHour; }    public long priceCents(Ticket ticket, Instant leftAt) {        long seconds = Duration.between(ticket.enteredAt(), leftAt).getSeconds();        long startedHours = Math.max(1, (seconds + 3599) / 3600);        return startedHours * centsPerHour.get(ticket.spot().size());    }}final class FlatPricing implements Pricing {    private final long cents;    FlatPricing(long cents) { this.cents = cents; }    public long priceCents(Ticket ticket, Instant leftAt) { return cents; }}interface Payments { void charge(String key, long cents); } // may throw PaymentDeclinedfinal class ParkingLot {    private final SpotPool pool;    private final Pricing pricing;    private final Payments payments;    private final java.util.function.Supplier<Instant> now;    private final Object lock = new Object();    private final Map<Long, Ticket> active = new HashMap<>();    private final Set<String> inside = new HashSet<>();    private long nextId = 1;    ParkingLot(List<Spot> spots, Pricing pricing, Payments payments,               java.util.function.Supplier<Instant> now) {        this.pool = new SpotPool(spots);        this.pricing = pricing;        this.payments = payments;        this.now = now;    }    Optional<Ticket> enter(Vehicle vehicle) {        synchronized (lock) {            if (inside.contains(vehicle.plate())) throw new AlreadyInside(vehicle.plate());            Optional<Spot> spot = pool.claim(vehicle.type().minSize);            if (spot.isEmpty()) return Optional.empty();            Ticket ticket = new Ticket(nextId++, vehicle, spot.get(), now.get());            inside.add(vehicle.plate());            active.put(ticket.id(), ticket);            return Optional.of(ticket);        }    }    Receipt leave(long ticketId) {        Ticket ticket;        synchronized (lock) { ticket = active.remove(ticketId); }        if (ticket == null) throw new UnknownTicket(ticketId);        Instant leftAt;        long cents;        try {            leftAt = now.get();            cents = pricing.priceCents(ticket, leftAt);            payments.charge("ticket-" + ticketId, cents);        } catch (RuntimeException e) {            synchronized (lock) { active.put(ticketId, ticket); }            throw e;        }        synchronized (lock) {            pool.release(ticket.spot());            inside.remove(ticket.vehicle().plate());        }        return new Receipt(ticket, leftAt, cents);    }    Map<SpotSize, Integer> free() {        synchronized (lock) { return pool.counts(); }    }}public class Main {    static Instant time = Instant.parse("2026-07-04T09:00:00Z");    public static void main(String[] args) {        List<Spot> spots = List.of(            new Spot("S1", 1, SpotSize.SMALL), new Spot("M1", 1, SpotSize.MEDIUM),            new Spot("M2", 1, SpotSize.MEDIUM), new Spot("M3", 1, SpotSize.MEDIUM),            new Spot("L1", 1, SpotSize.LARGE));        Map<SpotSize, Long> rates = Map.of(            SpotSize.SMALL, 100L, SpotSize.MEDIUM, 200L, SpotSize.LARGE, 500L);        Map<String, Long> charged = new HashMap<>();        Payments cards = (key, cents) -> charged.putIfAbsent(key, cents);        ParkingLot lot = new ParkingLot(spots, new HourlyPricing(rates), cards, () -> time);        Ticket red = lot.enter(new Vehicle("RED-1", VehicleType.CAR)).orElseThrow();        Ticket moto = lot.enter(new Vehicle("MOTO-1", VehicleType.MOTORCYCLE)).orElseThrow();        Ticket bus = lot.enter(new Vehicle("BUS-1", VehicleType.BUS)).orElseThrow();        Ticket second = lot.enter(new Vehicle("MOTO-2", VehicleType.MOTORCYCLE)).orElseThrow();        System.out.println(red.spot().id() + " " + moto.spot().id() + " " + bus.spot().id() + " " + second.spot().id());        System.out.println(lot.enter(new Vehicle("BUS-2", VehicleType.BUS)).isPresent());        time = time.plus(Duration.ofMinutes(130));        System.out.println(lot.leave(red.id()).cents());    }}
The same in C++
#include <algorithm>#include <array>#include <chrono>#include <cstdint>#include <deque>#include <functional>#include <iostream>#include <map>#include <mutex>#include <optional>#include <set>#include <stdexcept>#include <string>#include <vector>enum class SpotSize { Small, Medium, Large };constexpr std::array<SpotSize, 3> kSizes{SpotSize::Small, SpotSize::Medium, SpotSize::Large};enum class VehicleType { Motorcycle, Car, Bus };constexpr SpotSize minSize(VehicleType type) {    switch (type) {        case VehicleType::Motorcycle: return SpotSize::Small;        case VehicleType::Car: return SpotSize::Medium;        case VehicleType::Bus: return SpotSize::Large;    }    throw std::logic_error("unknown vehicle type");}using Time = std::chrono::system_clock::time_point;struct Vehicle { std::string plate; VehicleType type; };struct Spot { std::string id; int level; SpotSize size; };struct Ticket { std::int64_t id; Vehicle vehicle; Spot spot; Time enteredAt; };struct Receipt { Ticket ticket; Time leftAt; std::int64_t cents; };struct AlreadyInside : std::runtime_error { using std::runtime_error::runtime_error; };struct UnknownTicket : std::runtime_error { using std::runtime_error::runtime_error; };struct PaymentDeclined : std::runtime_error { using std::runtime_error::runtime_error; };// The free spaces, one queue per size. The caller holds the lot's lock.class SpotPool {    std::map<SpotSize, std::deque<Spot>> free_;public:    explicit SpotPool(const std::vector<Spot>& spots) {        for (SpotSize size : kSizes) free_[size];        for (const Spot& spot : spots) free_[spot.size].push_back(spot);    }    std::optional<Spot> claim(SpotSize smallest) {        for (SpotSize size : kSizes) {            auto& queue = free_[size];            if (size < smallest || queue.empty()) continue;            Spot spot = queue.front();            queue.pop_front();            return spot;        }        return std::nullopt;    }    void release(const Spot& spot) { free_[spot.size].push_front(spot); }    std::map<SpotSize, std::size_t> counts() const {        std::map<SpotSize, std::size_t> out;        for (const auto& [size, queue] : free_) out[size] = queue.size();        return out;    }};struct Pricing {    virtual ~Pricing() = default;    virtual std::int64_t priceCents(const Ticket& ticket, Time leftAt) const = 0;};class HourlyPricing : public Pricing {    std::map<SpotSize, std::int64_t> centsPerHour_;public:    explicit HourlyPricing(std::map<SpotSize, std::int64_t> rates) : centsPerHour_(std::move(rates)) {}    std::int64_t priceCents(const Ticket& ticket, Time leftAt) const override {        auto seconds = std::chrono::duration_cast<std::chrono::seconds>(leftAt - ticket.enteredAt).count();        std::int64_t startedHours = std::max<std::int64_t>(1, (seconds + 3599) / 3600);        return startedHours * centsPerHour_.at(ticket.spot.size);    }};class FlatPricing : public Pricing {    std::int64_t cents_;public:    explicit FlatPricing(std::int64_t cents) : cents_(cents) {}    std::int64_t priceCents(const Ticket&, Time) const override { return cents_; }};struct Payments {    virtual ~Payments() = default;    virtual void charge(const std::string& key, std::int64_t cents) = 0;  // may throw PaymentDeclined};class ParkingLot {    SpotPool pool_;    const Pricing& pricing_;    Payments& payments_;    std::function<Time()> now_;    std::mutex lock_;    std::map<std::int64_t, Ticket> active_;    std::set<std::string> inside_;    std::int64_t nextId_ = 1;public:    ParkingLot(const std::vector<Spot>& spots, const Pricing& pricing, Payments& payments,               std::function<Time()> now)        : pool_(spots), pricing_(pricing), payments_(payments), now_(std::move(now)) {}    std::optional<Ticket> enter(const Vehicle& vehicle) {        std::lock_guard<std::mutex> hold(lock_);        if (inside_.count(vehicle.plate)) throw AlreadyInside(vehicle.plate);        std::optional<Spot> spot = pool_.claim(minSize(vehicle.type));        if (!spot) return std::nullopt;        Ticket ticket{nextId_++, vehicle, *spot, now_()};        inside_.insert(vehicle.plate);        active_.emplace(ticket.id, ticket);        return ticket;    }    Receipt leave(std::int64_t ticketId) {        std::optional<Ticket> ticket;        {            std::lock_guard<std::mutex> hold(lock_);            auto found = active_.find(ticketId);            if (found == active_.end()) throw UnknownTicket("ticket " + std::to_string(ticketId));            ticket = found->second;            active_.erase(found);        }        try {            Time leftAt = now_();            std::int64_t cents = pricing_.priceCents(*ticket, leftAt);            payments_.charge("ticket-" + std::to_string(ticketId), cents);            std::lock_guard<std::mutex> hold(lock_);            pool_.release(ticket->spot);            inside_.erase(ticket->vehicle.plate);            return Receipt{*ticket, leftAt, cents};        } catch (const std::exception&) {            std::lock_guard<std::mutex> hold(lock_);            active_.emplace(ticketId, *ticket);            throw;        }    }    std::map<SpotSize, std::size_t> free() {        std::lock_guard<std::mutex> hold(lock_);        return pool_.counts();    }};struct CardMachine : Payments {    std::map<std::string, std::int64_t> charged;    void charge(const std::string& key, std::int64_t cents) override { charged.emplace(key, cents); }};int main() {    std::vector<Spot> spots{{"S1", 1, SpotSize::Small}, {"M1", 1, SpotSize::Medium},                            {"M2", 1, SpotSize::Medium}, {"M3", 1, SpotSize::Medium},                            {"L1", 1, SpotSize::Large}};    HourlyPricing pricing({{SpotSize::Small, 100}, {SpotSize::Medium, 200}, {SpotSize::Large, 500}});    CardMachine cards;    Time time{};    ParkingLot lot(spots, pricing, cards, [&] { return time; });    Ticket red = *lot.enter({"RED-1", VehicleType::Car});    Ticket moto = *lot.enter({"MOTO-1", VehicleType::Motorcycle});    Ticket bus = *lot.enter({"BUS-1", VehicleType::Bus});    Ticket second = *lot.enter({"MOTO-2", VehicleType::Motorcycle});    std::cout << red.spot.id << ' ' << moto.spot.id << ' ' << bus.spot.id << ' ' << second.spot.id << '\n';    std::cout << lot.enter({"BUS-2", VehicleType::Bus}).has_value() << '\n';    time += std::chrono::minutes(130);    std::cout << lot.leave(red.id).cents << '\n';}
The same in TypeScript
enum SpotSize { Small = 1, Medium = 2, Large = 3 }const SIZES = [SpotSize.Small, SpotSize.Medium, SpotSize.Large] as const;type VehicleType = "motorcycle" | "car" | "bus";const MIN_SIZE: Record<VehicleType, SpotSize> = {  motorcycle: SpotSize.Small,  car: SpotSize.Medium,  bus: SpotSize.Large,};interface Vehicle { readonly plate: string; readonly type: VehicleType }interface Spot { readonly id: string; readonly level: number; readonly size: SpotSize }interface Ticket { readonly id: number; readonly vehicle: Vehicle; readonly spot: Spot; readonly enteredAt: Date }interface Receipt { readonly ticket: Ticket; readonly leftAt: Date; readonly cents: number }class AlreadyInside extends Error {}class UnknownTicket extends Error {}class PaymentDeclined extends Error {}/** The free spaces, one queue per size. */class SpotPool {  private readonly queues = new Map<SpotSize, Spot[]>(SIZES.map((size) => [size, []]));  constructor(spots: readonly Spot[]) {    for (const spot of spots) this.queue(spot.size).push(spot);  }  claim(smallest: SpotSize): Spot | null {    for (const size of SIZES) {      if (size < smallest) continue;      const spot = this.queue(size).shift();      if (spot) return spot;    }    return null;  }  release(spot: Spot): void {    this.queue(spot.size).unshift(spot);  }  counts(): Map<SpotSize, number> {    return new Map(SIZES.map((size) => [size, this.queue(size).length]));  }  private queue(size: SpotSize): Spot[] {    const queue = this.queues.get(size);    if (!queue) throw new Error("no queue for size " + size);    return queue;  }}interface Pricing { priceCents(ticket: Ticket, leftAt: Date): number }class HourlyPricing implements Pricing {  constructor(private readonly centsPerHour: Record<SpotSize, number>) {}  priceCents(ticket: Ticket, leftAt: Date): number {    const seconds = Math.floor((leftAt.getTime() - ticket.enteredAt.getTime()) / 1000);    const startedHours = Math.max(1, Math.ceil(seconds / 3600));    return startedHours * this.centsPerHour[ticket.spot.size];  }}class FlatPricing implements Pricing {  constructor(private readonly cents: number) {}  priceCents(): number { return this.cents; }}interface Payments { charge(key: string, cents: number): Promise<void> } // may reject with PaymentDeclinedclass ParkingLot {  private readonly pool: SpotPool;  private readonly active = new Map<number, Ticket>();  private readonly inside = new Set<string>();  private nextId = 1;  constructor(    spots: readonly Spot[],    private readonly pricing: Pricing,    private readonly payments: Payments,    private readonly now: () => Date,  ) {    this.pool = new SpotPool(spots);  }  // No await inside: the event loop runs this method from start to end, so it needs no lock.  enter(vehicle: Vehicle): Ticket | null {    if (this.inside.has(vehicle.plate)) throw new AlreadyInside(vehicle.plate);    const spot = this.pool.claim(MIN_SIZE[vehicle.type]);    if (!spot) return null;    const ticket: Ticket = { id: this.nextId++, vehicle, spot, enteredAt: this.now() };    this.inside.add(vehicle.plate);    this.active.set(ticket.id, ticket);    return ticket;  }  // There is an await, so the ticket is taken out of the map first.  async leave(ticketId: number): Promise<Receipt> {    const ticket = this.active.get(ticketId);    if (!ticket) throw new UnknownTicket("ticket " + ticketId);    this.active.delete(ticketId);    try {      const leftAt = this.now();      const cents = this.pricing.priceCents(ticket, leftAt);      await this.payments.charge("ticket-" + ticketId, cents);      this.pool.release(ticket.spot);      this.inside.delete(ticket.vehicle.plate);      return { ticket, leftAt, cents };    } catch (error) {      this.active.set(ticketId, ticket);      throw error;    }  }  free(): Map<SpotSize, number> {    return this.pool.counts();  }}let time = new Date("2026-07-04T09:00:00Z");const charged = new Map<string, number>();const cards: Payments = {  async charge(key, cents) {    if (!charged.has(key)) charged.set(key, cents);  },};const spots: Spot[] = [  { id: "S1", level: 1, size: SpotSize.Small },  { id: "M1", level: 1, size: SpotSize.Medium },  { id: "M2", level: 1, size: SpotSize.Medium },  { id: "M3", level: 1, size: SpotSize.Medium },  { id: "L1", level: 1, size: SpotSize.Large },];const rates = { [SpotSize.Small]: 100, [SpotSize.Medium]: 200, [SpotSize.Large]: 500 };const lot = new ParkingLot(spots, new HourlyPricing(rates), cards, () => time);const red = lot.enter({ plate: "RED-1", type: "car" });const moto = lot.enter({ plate: "MOTO-1", type: "motorcycle" });const bus = lot.enter({ plate: "BUS-1", type: "bus" });const second = lot.enter({ plate: "MOTO-2", type: "motorcycle" });console.log(red?.spot.id, moto?.spot.id, bus?.spot.id, second?.spot.id);console.log(lot.enter({ plate: "BUS-2", type: "bus" }));time = new Date(time.getTime() + 130 * 60_000);if (red) lot.leave(red.id).then((receipt) => console.log(receipt.cents));