This article first appeared on AlgoSimplified. That URL is canonical. The full lesson has the class diagram, the complete Python, exercises and a short quiz. This is a shorter cut of the same design.
Parking lot is a common low-level design interview problem. The useful work at the start is to fix the scope, separate the two policies that change from lot to lot, and make the find-and-occupy path atomic.
A reasonable interview scope
- Several floors, each with spots in three sizes: small (motorcycle), medium (car), large (truck or bus).
- A vehicle may use a spot of its size or a larger one.
- On entry, issue a ticket with the spot and the entry time; reject the vehicle when nothing fits.
- On exit, compute an hourly fee (rate depends on vehicle type; partial hours round up, minimum one hour) and free the spot.
- Several entry and exit gates run at the same time.
- A display board needs free-spot counts.
Leave payments, reservations, EV charging and valet as extensions unless the interviewer asks for them.
Nouns: ParkingLot, Floor, Spot, Vehicle, VehicleType, Ticket, Gate, PricingStrategy, Payment, DisplayBoard. Verbs: park, leave, findSpot, calculateFee, countFree.
Policies that vary
Two policies change from lot to lot:
- How a spot is chosen: nearest to the entrance, lowest floor, smallest fit, reserved EV spots. That is a
SpotAllocator. - How a stay is priced: hourly, flat daily, weekend rates, monthly passes. That is a
PricingStrategy.
Both are injected into ParkingLot, so a mall and an airport can share the same core.
Rules that do not vary: a spot is free or holds exactly one vehicle; a plate has at most one open ticket; park and leave must be atomic, or two gates will hand out the same spot.
The live lesson has a Mermaid class diagram of this. In short, ParkingLot owns floors of spots, talks to a SpotAllocator and a PricingStrategy, and keeps open tickets keyed by plate.
The design in Python
"""Parking lot low-level design: multi-floor, spot sizes, tickets and pricing."""
import itertools
import math
import threading
from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import Enum
class Size(Enum):
SMALL = 1 # motorcycle
MEDIUM = 2 # car
LARGE = 3 # bus / truck
class VehicleType(Enum):
MOTORCYCLE = Size.SMALL
CAR = Size.MEDIUM
TRUCK = Size.LARGE
@dataclass(frozen=True)
class Vehicle:
plate: str
type: VehicleType
@dataclass
class Spot:
id: str
size: Size
vehicle: Vehicle | None = None
def fits(self, v: Vehicle) -> bool:
return self.vehicle is None and self.size.value >= v.type.value.value
@dataclass
class Floor:
number: int
spots: list[Spot]
@dataclass
class Ticket:
id: int
vehicle: Vehicle
spot: Spot
entry_hour: float
exit_hour: float | None = None
fee: float | None = None
class PricingStrategy(ABC):
@abstractmethod
def fee(self, ticket: Ticket, hours: float) -> float: ...
class HourlyPricing(PricingStrategy):
RATES = {VehicleType.MOTORCYCLE: 10, VehicleType.CAR: 30, VehicleType.TRUCK: 60}
def fee(self, ticket, hours):
billable = max(1, math.ceil(hours)) # first hour always charged, then per started hour
return billable * self.RATES[ticket.vehicle.type]
class SpotAllocator(ABC):
@abstractmethod
def find(self, floors: list[Floor], v: Vehicle) -> Spot | None: ...
class SmallestFitFirst(SpotAllocator):
"""Lowest floor first, and the smallest spot that fits, so big spots stay free for big vehicles."""
def find(self, floors, v):
for floor in floors:
candidates = [s for s in floor.spots if s.fits(v)]
if candidates:
return min(candidates, key=lambda s: s.size.value)
return None
class ParkingFullError(Exception):
pass
class ParkingLot:
def __init__(self, floors, allocator: SpotAllocator, pricing: PricingStrategy):
self.floors, self.allocator, self.pricing = floors, allocator, pricing
self.active: dict[str, Ticket] = {} # plate -> open ticket
self._ids = itertools.count(1)
self._lock = threading.Lock() # entry gates run concurrently
def park(self, v: Vehicle, hour: float) -> Ticket:
with self._lock:
if v.plate in self.active:
raise ValueError(f"{v.plate} is already parked")
spot = self.allocator.find(self.floors, v)
if spot is None:
raise ParkingFullError(f"no spot for {v.type.name}")
spot.vehicle = v
ticket = Ticket(next(self._ids), v, spot, hour)
self.active[v.plate] = ticket
return ticket
def leave(self, plate: str, hour: float) -> Ticket:
with self._lock:
ticket = self.active.pop(plate)
ticket.exit_hour = hour
ticket.fee = self.pricing.fee(ticket, hour - ticket.entry_hour)
ticket.spot.vehicle = None
return ticket
def free_spots(self) -> dict[Size, int]:
counts = {s: 0 for s in Size}
for f in self.floors:
for s in f.spots:
if s.vehicle is None:
counts[s.size] += 1
return counts
if __name__ == "__main__":
floors = [Floor(0, [Spot("0-S1", Size.SMALL), Spot("0-M1", Size.MEDIUM), Spot("0-L1", Size.LARGE)]),
Floor(1, [Spot("1-M1", Size.MEDIUM), Spot("1-M2", Size.MEDIUM)])]
lot = ParkingLot(floors, SmallestFitFirst(), HourlyPricing())
t1 = lot.park(Vehicle("KA01", VehicleType.CAR), hour=9.0)
t2 = lot.park(Vehicle("KA02", VehicleType.MOTORCYCLE), hour=9.5)
t3 = lot.park(Vehicle("KA03", VehicleType.TRUCK), hour=10.0)
for t in (t1, t2, t3):
print(f"ticket {t.id}: {t.vehicle.plate} -> spot {t.spot.id}")
try:
lot.park(Vehicle("KA04", VehicleType.TRUCK), hour=10.5)
except ParkingFullError as e:
print("rejected:", e)
done = lot.leave("KA01", hour=11.25)
print(f"KA01 paid Rs {done.fee} for {done.exit_hour - done.entry_hour} h")
print("free:", {s.name: n for s, n in lot.free_spots().items()})
Output:
ticket 1: KA01 -> spot 0-M1
ticket 2: KA02 -> spot 0-S1
ticket 3: KA03 -> spot 0-L1
rejected: no spot for TRUCK
KA01 paid Rs 90 for 2.25 h
free: {'SMALL': 0, 'MEDIUM': 3, 'LARGE': 0}
What the run shows:
-
VehicleTypemaps each vehicle to the minimum size it needs, soSpot.fitsis one comparison. -
SmallestFitFirstscans from the lowest floor and picks the smallest fitting spot. The car took the medium spot even though the large one was free, which is the point of the policy: keep large spots for trucks. - The second truck is rejected with a domain exception, not a
Nonethe caller might ignore. - KA01 stayed 2.25 hours. Per-started-hour billing is 3 hours × Rs 30 = Rs 90.
- One lock wraps "find, occupy, record the ticket". Without it, two gates can both see
0-M1free and both assign it.
Scaling the design
- Finding a spot in O(1): keep a free-spot set or min-heap per size per floor.
parkpops,leavepushes back. - Finer locking: one lock per size class or per floor, with a consistent lock order so you don't deadlock.
- Persistence: the "find and occupy" step becomes a conditional update (
UPDATE spot SET plate=? WHERE id=? AND plate IS NULL) so the database picks one winner. - Display boards can subscribe to spot changes (observer).
In an interview, it helps to spend the first few minutes on requirements, draw the classes before coding, name the two strategies, and raise concurrency without being prompted.
The class diagram, exercises (free-spot sets, flat daily pricing, EV spots that do not touch ParkingLot) and a short quiz are in the full parking lot lesson, part of the free Low-Level Design course.
Top comments (0)