LLD: Design a Parking Lot
System Design · Low-Level Design · Intermediate · 25 min
Design and code the most asked machine-coding problem: spots of different sizes, a fair rule for picking a spot, tickets, hourly fees with a pricing strategy, and the follow-ups interviewers love (floors, EV spots, many gates at once).
A mall basement with three painted rows: small bike bays, normal car bays, wide truck bays. A guard at the gate looks at your vehicle, points you to the nearest free bay that fits, and hands you a ticket with the time stamped on it.
The idea in everyday words
Think of a cloakroom with small, medium and large hooks. A scarf can hang on any hook, but a big winter coat only fits a large one. The attendant always uses the nearest free hook that fits and gives you a token with a number. When you return the token, they read the time on it and charge you.
Requirements: ask before you code
"Design a parking lot" is deliberately vague. Spend 3 to 5 minutes pinning it down. Every answer changes the code.
| Question | Our answer for this lesson |
|---|---|
| Which vehicles? | bike, car, truck |
| Which spot sizes? | bike, car, truck spots, numbered from 1 |
| Can a small vehicle use a bigger spot? | Yes: a bike may use a car or truck spot if its own size is full; a car may use a truck spot. Never the other way. |
| Which spot do we give? | Own size first, then the next size up; inside a size, the lowest number (nearest the gate). |
| How do we charge? | By vehicle type, per started hour, minimum one hour: bike 10, car 20, truck 50. |
| Floors, gates, payments, EV charging? | Not now. Mention them as extensions. |
Must have: park, leave (with fee), show free spots. Errors: unknown vehicle, plate already inside, plate not found, lot full.
Write these as comments at the top of your file. When the interviewer later says "what about...?", you can point at the list.
Entities and the class diagram
Nouns from the requirements: lot, spot, vehicle, ticket, fee. Each becomes a class only if it has data and behaviour; otherwise it can stay a plain value.
ParkingLot
├─ spots: size -> [Spot] (composition: the lot owns its spots)
├─ tickets: plate -> Ticket (only vehicles that are inside)
├─ pricing: PricingStrategy (injected, so it can be swapped)
├─ park(plate, kind, now) -> text
├─ leave(plate, now) -> text
└─ status() -> text
Spot { id "car-2", size, plate or empty }
Ticket { plate, kind, spot, start time }
PricingStrategy <|── HourlyPricing { fee(kind, minutes) }
| Class | Responsibility | Why it exists |
|---|---|---|
| ParkingLot | Owns spots and tickets, enforces the rules | the one place that changes state |
| Spot | Knows its size and who is in it | lets the lot answer "is it free?" |
| Ticket | Remembers where and when a vehicle entered | the fee needs the start time and kind |
| HourlyPricing | Turns kind and minutes into money | a Strategy: weekend or flat-rate pricing is a new class |
Vehicle here is just a plate and a kind, so it is stored on the Ticket. In a bigger design it becomes its own class (with an EV flag, a handicap permit, and so on).
The two rules that matter: finding a spot and charging
Finding a spot. Keep a "fits" table from vehicle kind to the sizes it may use, smallest first:
| Vehicle | Tries, in order |
|---|---|
| bike | bike → car → truck |
| car | car → truck |
| truck | truck |
Walk that list and take the first free spot with the lowest number. When a car leaves car-1, the next car gets car-1 again, not car-3. That is what "nearest the gate" means, and it is a common test.
Charging. Charge per started hour, with a minimum of one hour, at the rate of the vehicle (a bike parked in a truck spot still pays the bike rate). A started hour is a ceiling division:
for minutes in [0, 45, 60, 61, 130]:
hours = max(1, (minutes + 59) // 60) # ceil(minutes / 60), at least 1
print(minutes, "min ->", hours, "h ->", hours * 20, "rupees for a car")
Put this rule in a pricing strategy object that the lot receives in its constructor. Weekend rates, a free first 15 minutes or a monthly pass then become new classes and the lot does not change.
Follow-ups the interviewer will ask
Once the basic version runs, expect one or two of these. Answer by pointing at the class you would change.
| Follow-up | Where it goes |
|---|---|
| Several floors | A Level class owns its spots; the lot asks levels in order. find_spot moves into Level. |
| EV charging spots | A spot gets a features set; the fits rule checks "needs charger". Pricing adds a charging fee strategy. |
| Display board at the entrance | Observer: the lot publishes "spot freed / taken" events, the board subscribes and updates its counts. |
| Pay by card or UPI at exit | A PaymentProcessor interface with one class per method. leave() asks it to charge the fee. |
| Lost ticket | Look up by plate (we already key tickets by plate) and charge a fixed penalty strategy. |
| Reserve a spot in advance | A spot gets a reserved state with an expiry; find_spot skips reserved spots that are not yours. |
Do not build these up front. Mention that your design leaves room for them: that is what the interviewer is checking.
Go deeper: many gates, fast lookups, real storage
- Several entry gates at once (concurrency). Two gates call find_spot at the same moment and both see car-1 free. Fix: make "find and take" atomic. Options: one lock around park and leave (simple, fine for one lot); one lock per level; or a compare-and-set on the spot ("set plate only if it is still empty") and retry if it fails. In a database, a conditional update
UPDATE spot SET plate = ? WHERE id = ? AND plate IS NULLdoes the same. - Fast free-spot lookup. Scanning every spot is O(n). Keep a min-heap of free spot numbers per size: taking the lowest free spot and returning one are both O(log n). For counts on a display board, keep a free counter per size.
- Idempotent exit. If the exit gate retries "leave KA01" after a network blip, the second call must not charge twice. Our version returns "not found" the second time; a real system would store the closed ticket and return the same receipt.
- Persistence. Behind a
TicketRepositoryinterface, the in-memory dictionary can become a table. The lot logic does not change. - Clock. We pass
nowinto every call instead of reading the system time. That keeps the code testable and makes "what if the clock jumps?" a question you can answer.
Step by step
- Two cars arrive:
Lot: 1 bike spot, 2 car spots, 1 truck spot. park KA01 car 0 → car-1 (lowest free car spot). park KA02 car 10 → car-2. Each gets a Ticket with its start time.
- Bikes fill up:
park MH03 bike 15 → bike-1. park DL04 bike 20: bike spots are full, so try car (full too), then truck: DL04 gets truck-1.
- Lot full for a car:
park TN05 car 25: car spots full, truck spot taken by the bike. A car may never use a bike spot, so the answer is 'full TN05'.
- KA01 leaves and pays:
leave KA01 130: 130 minutes is 3 started hours (130 + 59) // 60 = 3, at the car rate 20: 'left KA01 from car-1 paid 60'. car-1 is free again.
- The freed spot is reused:
park TN05 car 140: the lowest free car spot is car-1 again, so TN05 gets car-1, not a new number.
- Bike pays the bike rate:
leave DL04 200: 180 minutes = 3 hours at the BIKE rate 10, so 30, even though it sat in a truck spot. status: 'free bike:0 car:0 truck:1'.
Code example
class DisplayBoard: # Observer: reacts to lot events
def __init__(self, free):
self.free = dict(free)
def on_event(self, kind, size):
self.free[size] += 1 if kind == "freed" else -1
print(f" board: {self.free}")
class Lot:
def __init__(self, free):
self.listeners = []
self.free = dict(free)
def subscribe(self, listener):
self.listeners.append(listener)
def _emit(self, kind, size):
for listener in self.listeners:
listener.on_event(kind, size)
def take(self, size):
if self.free[size] == 0:
print(f"take {size}: none free")
return
self.free[size] -= 1
print(f"take {size}")
self._emit("taken", size)
def release(self, size):
self.free[size] += 1
print(f"release {size}")
self._emit("freed", size)
lot = Lot({"bike": 1, "car": 2})
lot.subscribe(DisplayBoard({"bike": 1, "car": 2}))
lot.take("car")
lot.take("car")
lot.take("car")
lot.release("car")Complexity
- Time: park O(S) to scan S spots (O(log S) with a min-heap per size); leave and status O(1) / O(S)
- Space: O(S + V): one object per spot and one ticket per parked vehicle
Interview tips
Open with questions: vehicle types, spot sizes, can small use big, how to pick a spot, how to charge. Write the answers as rules before any class.
Draw ParkingLot, Spot, Ticket and a PricingStrategy. Say out loud that pricing is injected so it can change without touching the lot.
Keep FITS and RATES as data tables. When asked 'add a van', show it is one line in each table.
Expect 'two cars enter from two gates at the same time'. Answer: find-and-take must be atomic: a lock, or a conditional update that only succeeds if the spot is still empty.
If you have time, mention the min-heap of free spots per size for O(log n) allocation and an Observer for the display board.
Challenge: Parking Lot Machine-Coding Round
Write run_parking_lot(capacity_by_type, ops). capacity_by_type gives the number of spots per size, for example {"bike": 1, "car": 2, "truck": 1} (a missing size has 0 spots). Spots are named <size>-<n> with n from 1. ops is a list of commands; return one output line per command.
| Command | Output |
|---|---|
park <plate> <kind> <minute> |
parked <plate> at <spot>, or full <plate> |
leave <plate> <minute> |
left <plate> from <spot> paid <fee> |
status |
free bike:<n> car:<n> truck:<n> (always these three, in this order) |
Rules:
- Which spot: a bike tries bike, then car, then truck spots; a car tries car, then truck; a truck only truck spots. Inside a size, take the free spot with the lowest number.
- Fee: per started hour, at least 1 hour, at the rate of the vehicle kind: bike 10, car 20, truck 50.
- Errors:
error: unknown vehicle <kind>(not bike / car / truck),error: <plate> already parked,error: <plate> not found(on leave).
Use classes: a ParkingLot, a Spot, a Ticket and a pricing strategy.
Example:
run_parking_lot({"bike": 1, "car": 2, "truck": 1},
["park KA01 car 0", "park MH03 bike 15", "park DL04 bike 20", "leave DL04 200", "status"])
-> ["parked KA01 at car-1", "parked MH03 at bike-1", "parked DL04 at car-2",
"left DL04 from car-2 paid 30", "free bike:0 car:1 truck:1"]
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Design Parking System (Easy)
- Observer pattern, for the display board (Refactoring.Guru) (Easy)
- Seat Reservation Manager (lowest free number with a heap) (Medium)
More in Low-Level Design
- Low-Level Design: How to Approach the Round
- LLD: Design an Elevator System
- LLD: Design a Rate Limiter (Classes and Strategies)
- LLD: Design Splitwise (Expense Sharing)
- LLD: Design Movie Ticket Booking (BookMyShow)
Previous: Low-Level Design: How to Approach the Round · Next: LLD: Design an Elevator System