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

Reservations and expiry

Promises about the future

The point: a reservation promises capacity at a time, not a numbered space. The hard question is not the booking. It is the walk-in who arrives ten minutes before it.

Model

Promise a number, choose the space late

Promise capacity

  • Any medium space will do, chosen on arrival
  • A broken lamp or a car that stays too long hurts nobody in particular
  • One count per size and time
  • Walk-ins and bookings share the spaces

Promise M7

  • M7 must stand empty long before
  • If someone overstays in M7 the promise is broken, with twenty spaces free
  • Needed only for named spaces: charger, accessible, a customer's own
Python
import heapqimport itertoolsfrom dataclasses import dataclass@dataclassclass Hold:    id: int    plate: str    start: int            # minutes since midnight    end: int    used: bool = Falseclass ReservationBook:    """Promises capacity of one size, not a numbered space."""    def __init__(self, capacity: int, grace: int = 15) -> None:        self._capacity, self._grace = capacity, grace        self._holds: dict[int, Hold] = {}        self._expiry: list[tuple[int, int]] = []      # (minute, hold id)        self._ids = itertools.count(1)    def reserve(self, plate: str, start: int, end: int, now: int) -> int | None:        self._expire(now)        points = [start] + [h.start for h in self._holds.values() if start < h.start < end]        busiest = max(sum(h.start <= p < h.end for h in self._holds.values()) for p in points)        if busiest >= self._capacity:            return None        hold = Hold(next(self._ids), plate, start, end)        self._holds[hold.id] = hold        heapq.heappush(self._expiry, (start + self._grace, hold.id))        return hold.id    def arrive(self, hold_id: int, now: int) -> bool:        self._expire(now)        hold = self._holds.get(hold_id)        if hold is None or hold.used or now < hold.start - self._grace:            return False        hold.used = True        return True    def promised_soon(self, now: int, minutes: int = 60) -> int:        self._expire(now)        return sum(not h.used and h.start <= now + minutes for h in self._holds.values())    def _expire(self, now: int) -> None:        while self._expiry and self._expiry[0][0] < now:            hold = self._holds.get(heapq.heappop(self._expiry)[1])            if hold and not hold.used:                del self._holds[hold.id]book = ReservationBook(capacity=1)first = book.reserve("A", 600, 660, now=540)print(first, book.reserve("B", 630, 700, now=541), book.reserve("B", 660, 700, now=541))print(book.promised_soon(now=560), book.arrive(first, now=616), book.reserve("C", 620, 650, now=616))
reserve finds the busiest moment inside the wish: overlap can rise only where a booking starts, so only those moments are looked at. arrive at 616 fails, because the 15 minutes of grace ended at 615.
Edit and run it in your browser

Capacity 1

WishOverlapsAnswer
A 10:00 to 11:00nonebooking 1
B 10:30 to 11:40A, from 10:30 to 11:00no
B 11:00 to 11:40none: A ends at 11:00, and the end is not includedbooking 2
C 10:20 to 10:50, after A did not comenone: A expiredbooking 3

Walk-ins

Who may have the last space now?

A walk-in has no end time. If the last medium space goes to them at 09:50, the booking at 10:00 meets a full lot. So a walk-in may enter only if enough is left for what is promised soon.

The rule at the gate

walk-in  ⟺  free now−promised soon>0\text{walk-in} \iff \text{free now} - \text{promised soon} > 0
Soon means the next hour. 3 free, 2 promised before 11:00: one walk-in may enter, the next one is refused with two spaces empty. That is the price of a promise. The hour is a setting.

How do bookings and walk-ins share the lot?

BreaksFirst come, first served
How
Bookings are only entries in a list.
Limit
People with a booking meet a full lot.
Choose when
Never. It is not a reservation then.
WorksTwo separate parts
How
40 spaces for bookings, 260 for walk-ins, two pools.
Limit
One part is full while the other is empty.
Choose when
A simple start, and easy to explain on a sign.
StrongOne pool, look ahead
How
Count promises that begin soon and keep that many spaces back.
Limit
Needs a guess about how long people stay. Still fails when many overstay.
Choose when
Both groups are large. Measure how often a promise is broken.

Expiry

Nobody came

WayHowTrouble
LazyEvery call first removes what has expiredNothing happens if nobody calls; fine here, because nobody is asking
TimerA thread wakes for the earliest one in a heapA thread to start, stop and test
SweepEvery minute look through allUp to a minute late, O(n)
Store with expiryA key that deletes itself, such as SET key value NX EX 900Needs the store; the expiry is an event you may miss
We use lazy with a heap: each hold is pushed once and popped once, so the cost is O(log n) for each booking.

Arrive and expire at the same moment

Both change one hold under one lock, so one of them is first and the other finds out. Whichever it is, the driver gets a clear answer.

Edges

Say these before they ask

  1. 1

    Too early

    A driver who comes 40 minutes early is a walk-in. 15 minutes early is fine.

  2. 2

    Too long

    A booked hour becomes three. The price goes on. The next booking gets any other space: the reason for promising capacity.

  3. 3

    Cancel

    Cancelling twice is fine. Cancelling after arrival is refused.

  4. 4

    Overbooking

    Airlines sell more seats than they have. Here a broken promise is a person in a street, so start without it.