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

Ticket system

Ids, indexes and single use

The point: a ticket is a key to a departure and may be used once. remove returns it to exactly one caller. get followed by remove does not.

Structure

Three lookups, all O(1)

QuestionIndexAsked by
Which ticket is this?id to ticketExit gate
Is this plate inside?plate to idEntry gate, help desk
Who is in L1?space to ticket, if neededTowing, cleaning
Java
final class TicketService {    private final ConcurrentHashMap<Long, Ticket> active = new ConcurrentHashMap<>();    private final AtomicLong ids = new AtomicLong(1);    Ticket issue(Vehicle vehicle, Spot spot, Instant now) {        Ticket ticket = new Ticket(ids.getAndIncrement(), vehicle, spot, now);        active.put(ticket.id(), ticket);        return ticket;    }    /** The exit that gets the ticket owns the departure. Everyone else gets empty. */    Optional<Ticket> takeForExit(long id) { return Optional.ofNullable(active.remove(id)); }    int inside() { return active.size(); }   // fine for a sign, not for a decision}
ConcurrentHashMap and AtomicLong are safe one by one, without a lock of yours. takeForExit is one call, so two exit gates with a copied ticket cannot both win.
Python
import secretsfrom dataclasses import dataclass, field@dataclassclass TicketIndex:    """Three ways in, one truth. Change them together, under the lot's lock."""    by_id: dict[str, str] = field(default_factory=dict)      # id -> plate    by_plate: dict[str, str] = field(default_factory=dict)   # plate -> id    def issue(self, plate: str) -> str | None:        if plate in self.by_plate:            return None        ticket_id = secrets.token_urlsafe(12)                # 96 random bits: nobody guesses it        self.by_id[ticket_id] = plate        self.by_plate[plate] = ticket_id        return ticket_id    def take(self, ticket_id: str) -> str | None:        plate = self.by_id.pop(ticket_id, None)              # pop, never get and then delete        if plate is not None:            del self.by_plate[plate]        return plateindex = TicketIndex()first = index.issue("RED-1")print(index.issue("RED-1"), len(first))print(index.take(first), index.take(first))
Two indexes in one class. The second entry with the same plate is refused, and the second use of the ticket finds nothing.
Edit and run it in your browser

Ids

What goes on the paper

How do you make ticket ids?

BreaksPlate plus time
How
ABC-123-20260704
Limit
Twice on one day collides. It prints personal data on paper. Anybody can make one.
Choose when
Never.
WorksA counter
How
AtomicLong, 1, 2, 3.
Limit
Easy to guess: the paper says 41, so 40 exists. Starts again after a restart. Two machines give the same number.
Choose when
Inside one process, with the number as an internal name only.
StrongRandom, or a counter with a signature
How
96 random bits in the barcode, or 41. plus a short keyed signature that the gate checks.
Limit
Longer than a person can read aloud: print a short number beside it for the desk.
Choose when
Whenever the paper opens a barrier.

Fields

What a ticket holds, and what it does not

FieldOn the ticket?Reason
id, vehicle, space, entry timeYes, unchangingFacts of the entry
Exit time, amountNo, on the receiptNot known yet. A half-filled record invites mistakes
Paid flagNo, in the sessionIt changes, so it needs a lock or a status change
Price per hourPerhaps: the id of the tariffIf the price changes at noon, people who came before pay the old one
Entry time from the gate's own clockNoTwo gates disagree. One injected clock

Failure walk

Trouble with paper

What happensWhat the system does
Copied ticket at two exitsOne remove wins. The other: unknown ticket, call help
Printer jams after the claimPrint again: same id, same space. Or give the space back if the car turns round
The gate loses the answerIt asks again by plate and gets the same ticket, not a second space
RestartLoad active tickets from storage, then rebuild the free queues from them
A ticket from last monthNot active: refuse. Keep used ids, so the desk can say when it was used