Design a parking lot
medium 90 minModel 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.
| Order | Part | Minutes | If time runs out |
|---|---|---|---|
| 1 | Enums and records | 3 | Say the records, write the enums |
| 2 | Pool | 4 | Never skip: this is the core |
| 3 | Pricing and payment | 3 | One rule, the interface, stop |
| 4 | Enter | 4 | Never skip |
| 5 | Leave | 5 | Write the order as comments first |
| 6 | A run with real values | 3 | Trace 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.
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.
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
| Language | Record, nothing found, lock, money | Careful with |
|---|---|---|
| Python | Frozen dataclass, None, with lock, int. An interface is a Protocol, time an aware datetime in UTC | Equal enum values merge into one |
| Java | record, Optional, synchronized, long. Time is an Instant | Optional 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 destructor | The lot keeps references: the rule must live longer than the lot |
| TypeScript | readonly interface, null, no lock without an await, whole number | An await is a gap like a thread switch |
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.