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

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

StructureFind and takeGive backCountNearest?Memory
List of spaces, scannedup to 500 looks1500Yes, if sorted500
Queue by size1 to 3 looks13No500 references
Min-heap by distance, per sizelog2(500) is about 9 stepsabout 93Yes500 pairs
Sorted set (tree)about 9about 93Yes, and removing any one is about 9 toomore per entry
One bit per space1 machine word per 641popcountFirst in the row8 words for 500
The scan is worst exactly when it matters: on a full Saturday nearly every look is a taken space.

Nearest

A heap for each size

Python
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"))
The distance comes first in the pair, so the nearest is on top. Equal distances fall back to the name, which keeps tests stable. The lot's lock is held by the caller.
Edit and run it in your browser

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 claim rule.
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?

RuleGoodBad
Any larger sizeNo one is refused while something fitsMotorcycles in bus spaces
One size up at mostLarge spaces surviveA motorcycle is refused with large spaces free
Keep the last k large spacesBuses that are expected find roomSpaces stand empty on purpose
Offer it, with the higher price shownThe driver decides, and it can earn moneyA question at the barrier costs seconds
This is a policy. Ask, then put it in one method.

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.

Python
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))
The second version keeps a row in one integer. Shift and and: after four rounds a bit is still set only where five neighbours are free. For rows up to 64 spaces this is eight machine operations, whatever the row looks like.
Edit and run it in your browser