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
Finding a space fast
Free lists, heaps, fallback, runs
The point: keep what is free in the shape of the question you ask. Any? A queue by size. The nearest? A heap. Five in a row? A row of bits.
Scan
Why a walk is the wrong shape
500 spaces
| Structure | Find and take | Give back | Count | Nearest? | Memory |
|---|---|---|---|---|---|
| List of spaces, scanned | up to 500 looks | 1 | 500 | Yes, if sorted | 500 |
| Queue by size | 1 to 3 looks | 1 | 3 | No | 500 references |
| Min-heap by distance, per size | log2(500) is about 9 steps | about 9 | 3 | Yes | 500 pairs |
| Sorted set (tree) | about 9 | about 9 | 3 | Yes, and removing any one is about 9 too | more per entry |
| One bit per space | 1 machine word per 64 | 1 | popcount | First in the row | 8 words for 500 |
Nearest
A heap for each size
import heapqclass NearestPool: """Free spaces by size, nearest to the gate first.""" def __init__(self, spots: list[tuple[str, str, int]]) -> None: self._free: dict[str, list[tuple[int, str]]] = {"S": [], "M": [], "L": []} for spot_id, size, metres in spots: heapq.heappush(self._free[size], (metres, spot_id)) def claim(self, smallest: str) -> str | None: for size in "SML"["SML".index(smallest):]: # smallest fitting size first if self._free[size]: return heapq.heappop(self._free[size])[1] return None def release(self, spot_id: str, size: str, metres: int) -> None: heapq.heappush(self._free[size], (metres, spot_id))pool = NearestPool([("M1", "M", 40), ("M2", "M", 15), ("M3", "M", 60), ("L1", "L", 10)])print(pool.claim("M"), pool.claim("M")) # M2, then M1: never L1 while a medium is freepool.release("M2", "M", 15)print(pool.claim("M"), pool.claim("M"), pool.claim("M"), pool.claim("M"))Notice L1 in the example. It is the nearest space of all, and cars still get M2 and M1 first. Size before distance, or the buses find nothing. If the business prefers happy drivers to free large spaces, it is one change: compare distances across sizes.
Which space should a car get?
BreaksThe first free space in a list
- How
- Walk and take whatever fits.
- Limit
- Cars fill the large spaces near the door. The first bus is turned away from a lot that is half empty.
- Choose when
- Only if all spaces are equal.
WorksSmallest size, any space
- How
- Queue by size, search upwards.
- Limit
- A driver is sent to the far end while a space beside the door is free.
- Choose when
- The base design. Simple, O(1), easy to defend.
StrongSmallest size, then nearest, behind a rule
- How
- A heap by size, ordered by distance from that gate, chosen by a replaceable
claimrule. - Limit
- Several gates mean several distances: a heap for each gate, and lazy deletion of spaces taken through another one.
- Choose when
- When guidance matters. Say the price: one entry per gate per space.
Fallback
Upwards only, and how far?
| Rule | Good | Bad |
|---|---|---|
| Any larger size | No one is refused while something fits | Motorcycles in bus spaces |
| One size up at most | Large spaces survive | A motorcycle is refused with large spaces free |
| Keep the last k large spaces | Buses that are expected find room | Spaces stand empty on purpose |
| Offer it, with the higher price shown | The driver decides, and it can earn money | A question at the barrier costs seconds |
Runs
Five in a row
Count along the row: one more for a free space, back to zero for a taken one. When the count reaches five, the run has started four spaces earlier. It is O(n) with no memory. Two traps: the run must not cross the end of a row, and the spaces must be large.
def first_run(free: str, need: int) -> int | None: """Row of spaces, '.' free and 'x' taken. Index of the first run of `need` free ones.""" length = 0 for i, space in enumerate(free): length = length + 1 if space == "." else 0 if length == need: return i - need + 1 return Nonedef first_run_bits(bits: int, need: int) -> int | None: """The same with one bit per space (bit 0 is the first space, 1 = free).""" starts = bits for shift in range(1, need): starts &= bits >> shift # a start survives only if its neighbour is free too return (starts & -starts).bit_length() - 1 if starts else Nonerow = "x.....xx.."print(first_run(row, 5), first_run(row, 6))print(first_run_bits(sum(1 << i for i, c in enumerate(row) if c == "."), 5))