What you will learn
- How to run the six-step LLD method on the most common interview prompt.
- Where the strategy pattern fits (allocation and pricing).
- How to make concurrent entry gates safe.
- A complete, runnable parking lot implementation.
1. Clarify requirements
Ask before designing. A reasonable scope:
- Multiple floors; each floor has spots of three sizes: small (motorcycle), medium (car), large (truck/bus).
- A vehicle can use a spot of its size or larger.
- On entry, issue a ticket with the spot and entry time; reject when no spot fits.
- On exit, compute the fee (hourly, rate depends on vehicle type; partial hours round up, minimum one hour) and free the spot.
- Several entry and exit gates work concurrently.
- Show free spot counts (for the display board).
Out of scope unless asked: payments integration, reservations, EV charging, valet. Mention them as extensions.
2. Nouns and verbs
Nouns: ParkingLot, Floor, Spot, Vehicle, VehicleType, Ticket, Gate, PricingStrategy, Payment, DisplayBoard. Verbs: park, leave, findSpot, calculateFee, countFree.
3. Relationships
ParkingLot *-- "many" Floor *-- "many" Spot
ParkingLot --> SpotAllocator (interface) <|.. SmallestFitFirst
ParkingLot --> PricingStrategy (interface) <|.. HourlyPricing
ParkingLot "1" --> "many" Ticket (active, keyed by plate)
Ticket --> Vehicle, Ticket --> Spot
Spot --> Vehicle (0..1, current occupant)
4. What varies?
- How we choose a spot: nearest to the entrance, lowest floor, smallest fitting size, reserved spots for EVs. →
SpotAllocatorstrategy. - How we charge: hourly, flat daily, weekend rates, monthly passes. →
PricingStrategy.
Both are injected into ParkingLot, so a mall and an airport can reuse the same core.
5. State and rules
- A spot is free or holds exactly one vehicle.
- A plate can have at most one open ticket.
parkandleavemust be atomic: two gates must never assign the same spot.
6. The code
"""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, field
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}
Walk-through:
VehicleTypemaps each vehicle to the minimum spot size it needs, soSpot.fitsis one comparison.SmallestFitFirstscans floors from the bottom and picks the smallest fitting spot, keeping large spots for trucks. The car got the medium spot even though the large spot was also free.- The second truck is rejected with a domain exception, not a
Nonethe caller might forget to check. - KA01 stayed 2.25 hours; with per-started-hour billing that’s 3 hours × Rs 30 = Rs 90.
- One lock guards the “find spot + occupy it + record ticket” sequence. Without it, two gates could both see spot 0-M1 free and both assign it.
Scaling the design
- Finding a spot in O(1): instead of scanning, 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 allows more parallel gates. Keep the ordering consistent to avoid deadlocks.
- Multiple lots / persistence: tickets and spot occupancy move to a database; the “find and occupy” becomes a conditional update (
UPDATE spot SET plate=? WHERE id=? AND plate IS NULL) so the database guarantees one winner. - Display boards subscribe to spot changes (observer).
Interview tips
- Spend the first few minutes on requirements and say what you’re leaving out.
- Draw the class diagram before coding; name the two strategies explicitly.
- Mention concurrency yourself; it’s what separates a strong answer.
- Practise variants from the LLD sheet: EV charging, reservations, multiple entrances with nearest-spot allocation.
Key takeaways
- Model sizes and vehicle types as enums so fitting is a simple comparison.
- Put spot allocation and pricing behind strategy interfaces and inject them.
- Make the “find and occupy” step atomic; in a database, use a conditional update.
- Use free-spot sets or heaps when the lot is large.
Exercises
- Replace the scan in
SmallestFitFirstwith per-size free-spot sets and keep the same output. - Add a
FlatDailyPricingstrategy: Rs 200 per started 24 hours for cars, double for trucks. - Add EV spots that only electric cars may use, without changing
ParkingLot.
Quiz
- Why is spot allocation a strategy rather than code inside
ParkingLot? - What could go wrong without the lock in
park? - How much does a car pay for 1 hour 5 minutes with this pricing?
Show answers
- Allocation policies vary between lots (nearest, lowest floor, smallest fit); a strategy lets you swap them without editing
ParkingLot(Open/Closed). - Two gates could pick the same free spot at the same time and assign two vehicles to it.
- Rs 60: 1.08 hours rounds up to 2 billable hours at Rs 30.