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

Implementation

Line by line, in four languages

The point: write it in this order. Each part is complete before the next one needs it, and you can stop after any of them with something that makes sense.

OrderPartMinutesIf time runs out
1Enums and records3Say the records, write the enums
2Pool4Never skip: this is the core
3Pricing and payment3One rule, the interface, stop
4Enter4Never skip
5Leave5Write the order as comments first
6A run with real values3Trace by hand instead

First half

Values that do not change

Types and records: what must be remembered

Two fixed sets of values. The one fact that differs between vehicles, the smallest size that fits, is written next to the name.

import itertoolsfrom collections import dequefrom dataclasses import dataclassfrom datetime import datetime, timedelta, timezonefrom enum import Enum, IntEnumfrom threading import Lockfrom typing import Callable, Iterable, Protocolclass SpotSize(IntEnum):    SMALL = 1    MEDIUM = 2    LARGE = 3class VehicleType(Enum):    MOTORCYCLE = ("motorcycle", SpotSize.SMALL)    CAR = ("car", SpotSize.MEDIUM)    BUS = ("bus", SpotSize.LARGE)    @property    def min_size(self) -> SpotSize:        return self.value[1]

Lines 1 to 7

Nothing here is third party. Lock guards the lot, Callable is the type of the clock we pass in.

1 of 5

Why it is built this way

  • Two enums and not one, because they mean different things: what a vehicle is and what a space is. A medium space can hold a motorcycle.
  • A typo in a string is found by a customer. A typo in an enum is found by the editor.

Second half

Objects that do

The moving parts: pool, price, enter, leave

Free spaces, one queue per size. It is the only object that may hand out a space.

class SpotPool:    """The free spaces, one queue per size. The caller holds the lot's lock."""    def __init__(self, spots: Iterable[Spot]) -> None:        self._free: dict[SpotSize, deque[Spot]] = {size: deque() for size in SpotSize}        for spot in spots:            self._free[spot.size].append(spot)    def claim(self, smallest: SpotSize) -> Spot | None:        for size in SpotSize:                      # SMALL, MEDIUM, LARGE            if size >= smallest and self._free[size]:                return self._free[size].popleft()  # found and taken in one move        return None    def release(self, spot: Spot) -> None:        self._free[spot.size].appendleft(spot)    def counts(self) -> dict[SpotSize, int]:        return {size: len(queue) for size, queue in self._free.items()}

Line 2

The comment is a contract: who holds the lock. The pool has none of its own, so it cannot be used safely from outside the lot, and it is private there.

1 of 7

Why it is built this way

  • Claim and release are O(1): three sizes, a constant.
  • The pool speaks in sizes, not vehicles. Electric or accessible spaces will change it, and nobody else.

Languages

What differs, and why

LanguageRecord, nothing found, lock, moneyCareful with
PythonFrozen dataclass, None, with lock, int. An interface is a Protocol, time an aware datetime in UTCEqual enum values merge into one
Javarecord, Optional, synchronized, long. Time is an InstantOptional is for results, not for fields
C++struct by value, std::optional, lock_guard, int64_t. An interface is an abstract struct with a virtual destructorThe lot keeps references: the rule must live longer than the lot
TypeScriptreadonly interface, null, no lock without an await, whole numberAn await is a gap like a thread switch
In TypeScript enter needs no lock, because it runs from start to end without an await. leave has an await, so it removes the ticket first. The gap is the same, only the cause differs.