System design interview: design a parking lot
"Design a parking lot" asks you to model a garage: vehicles of different sizes, spots that fit some of them, tickets at the entrance and payment at the exit. It is usually an object-oriented design question, so the interview is about clean classes and responsibilities, a sensible spot-allocation rule, correct fee logic, and, if the interviewer scales it up, how many gates and garages share one system without giving the same spot away twice.
By Evin JohnPublished 8 min read
1. Clarify the requirements
This prompt has two common forms. In an object-oriented design round you write classes and a little code for one building. In a system design round you design the software for a chain of garages with gates, sensors and payments. Ask which one; the sections below cover the class model first and then the service around it.
- Functional: vehicles of three sizes (motorcycle, compact, large); spots of the same three sizes, possibly on several floors; a vehicle may use its own size or larger; issue a ticket at entry; charge at exit by duration; show free spots per floor on a display; reject entry when full.
- Non-functional: the barrier opens within a second or two; two cars never get the same spot; gates keep working during a network outage; prices can change without code changes.
- Ask about: reserved and disabled-access spots, electric charging spots, monthly pass holders, lost tickets, and whether the system assigns a spot or drivers choose freely.
2. Estimate the scale
| Quantity | Assumption | Result |
|---|---|---|
| Garages | 500 locations, about 1,000 spots each | 500,000 spots |
| Turnover | 3 vehicles per spot per day | 1.5 million tickets a day |
| Rate | 1.5 million / 86,400 seconds | about 17 entries a second on average, a few hundred at a big event's peak across the chain |
| Data | about 200 bytes per ticket | around 300 MB of tickets a day |
These are tiny numbers. Say so: the challenge is correctness and offline behavior at the gate, not throughput. That frees the rest of the interview for modeling.
3. Define the interface
ParkingLot.park(vehicle_size, now) -> ticket_id | None (full)
ParkingLot.leave(ticket_id, now) -> fee in cents (frees the spot)
ParkingLot.free_count(size, floor) -> int (for the entrance display)
POST /v1/garages/{g}/entries { gateId, plate?, vehicleSize, at } -> { ticketId, spotId? }
POST /v1/garages/{g}/exits { ticketId, at } -> { feeCents, paid }
GET /v1/garages/{g}/availability -> { bySize, byFloor }4. Sketch the classes
| Class | Responsibility | Key fields or methods |
|---|---|---|
Vehicle | Describes what arrived | plate, size |
Spot | A physical place | id, size, floor, distance from entrance, occupied flag |
ParkingLot | Allocates and frees spots; owns tickets | park, leave, free spots per size |
Ticket | Proof of entry | id, spot, entered_at, paid_at |
FeePolicy | Turns a stay into a price; swappable | fee(minutes); hourly, flat, event pricing |
EntryGate / ExitGate | Hardware adapters: read plate or button, print ticket, open barrier | talk to the lot, never decide prices themselves |
DisplayBoard | Shows free counts | subscribes to spot changes |
A common trap is a deep inheritance tree (Car extends Vehicle, CompactSpot extends Spot) where nothing differs except a size field. Prefer a size enum and composition; add subclasses only when behavior differs, such as an ElectricSpot that also controls a charger.
5. The core logic: allocate, free and price
import heapq, itertools
SIZES = ["motorcycle", "compact", "large"] # smallest to largest
class ParkingLot:
def __init__(self, spots):
"""spots: list of (spot_id, size, distance_from_entrance)."""
self.free = {s: [] for s in SIZES} # size -> heap of (distance, spot_id)
self.info = {}
for spot_id, size, dist in spots:
self.info[spot_id] = (size, dist)
heapq.heappush(self.free[size], (dist, spot_id))
self.tickets = {} # ticket_id -> (spot_id, entered_at)
self.ids = itertools.count(1)
def park(self, vehicle_size, now):
"""Nearest free spot of the smallest size that fits. Returns a ticket id or None."""
for size in SIZES[SIZES.index(vehicle_size):]:
if self.free[size]:
_, spot_id = heapq.heappop(self.free[size])
ticket = next(self.ids)
self.tickets[ticket] = (spot_id, now)
return ticket
return None # lot full for this vehicle
def leave(self, ticket, now, rate_cents=300, daily_cap_cents=2400):
spot_id, entered = self.tickets.pop(ticket) # KeyError = unknown or used ticket
size, dist = self.info[spot_id]
heapq.heappush(self.free[size], (dist, spot_id))
minutes = max(0, now - entered)
days, rest = divmod(minutes, 24 * 60)
hours = -(-rest // 60) # every started hour counts
return days * daily_cap_cents + min(hours * rate_cents, daily_cap_cents)- Smallest fitting size first keeps large spots free for large vehicles. A motorcycle takes a large spot only when no smaller one is left.
- Heaps make the choice O(log n) per park and leave, instead of scanning every spot. With several floors, keep one heap per floor and size, and pick the floor first.
- Fees in integer cents, never floating point. In a fuller design
leavedelegates to aFeePolicyobject so weekend or event pricing is a configuration change; the inline rate here keeps the example short. The rates are placeholders, not real prices. - Lost or reused tickets surface as an unknown ticket ID; the exit gate then charges a lost-ticket fee set by policy and logs it for review.
6. The architecture for a chain of garages
- Devices
- Entry and exit gates
- Plate cameras
- Payment terminals
- Spot sensors
- Display boards
- Garage
- Local controller (allocation, open tickets)
- Local database
- Outbound event queue
- Central
- Ticket and payment service
- Pricing and passes
- Availability API for apps
- Data
- Central database
- Reporting warehouse
Putting the allocation logic in a controller inside each garage is the key decision. Barriers must open even if the internet link is down, so the garage needs a working copy of its own state. Events flow to the central service through a queue and are replayed in order after an outage.
7. Concurrency and correctness
- One writer per garage. The local controller serializes allocations (a single thread or a lock around
parkandleave), so two gates cannot pop the same spot. At a few entries a second, this is never a bottleneck. - If allocation is central instead, claim a spot with a conditional update ("set occupied where id = ? and occupied = false") and retry with the next candidate if it fails. It is the same claim-or-retry idea used for seats in the ticket booking walk-through.
- Sensors beat assumptions. Drivers ignore assigned spots. Occupancy sensors correct the free map; the display uses sensor counts, while billing uses tickets.
- Idempotent events. A gate may resend an entry event after a timeout. Ticket IDs generated at the gate (garage ID plus a sequence) let the central service drop duplicates.
8. What breaks, and what you do about it
| Failure | Effect | Mitigation |
|---|---|---|
| Internet link down | Central service unreachable | Local controller keeps running; events queue locally and sync later |
| Payment terminal fails | Queue at the exit | Accept another method, open the barrier and bill by plate where allowed, or a staffed lane |
| Controller crashes | Gates stop | Restart from the local database; a hot standby controller; manual barrier override |
| Sensor reports wrong state | Display shows spaces that do not exist | Cross-check with ticket counts; flag sensors that disagree for maintenance |
| Event day rush | Long entry queue | Pre-paid event tickets read by plate camera; open all lanes as entries |
9. Trade-offs to discuss
- Assigned spots or free choice. Assignment balances floors and keeps large spots free; free choice is simpler and matches how most drivers behave.
- Inheritance or composition. Subclasses read nicely on a whiteboard but multiply for every combination (electric and large, reserved and compact); a size plus feature flags on
Spotstays flat. - Local or central allocation. Local survives outages; central gives one view across garages for reservations and apps.
- Ticket or plate. Plate recognition removes paper tickets but needs a fallback when a plate is unreadable, and raises data retention questions.
10. How to talk through it in the interview
Fictional example
- Interviewer
- Nice classes. Now we have 500 garages. What changes?
- Candidate
- The class model stays, but it runs in a controller inside each garage, because barriers have to work when the network does not. Each controller pushes ticket and payment events through a queue to a central service, which handles passes, pricing rules and the availability shown in the app. Load is small, about 17 entries a second across the chain, so the central side is a normal service with a relational database.
- Interviewer
- A customer reserves a spot in the app. How does the garage know?
- Candidate
- The central service sends the reservation to that garage's controller, which removes one spot of that size from its free heap until the reservation time passes or the plate camera sees the car.
- Start with requirements and a list of classes before writing any code.
- Write
parkandleave; they show allocation and pricing in a few lines. - Offer the scaled-up version yourself if time remains; it shows you can move between design levels.
The same interview family includes the vending machine (a state machine with money) and the elevator system (a scheduler), which test the same modeling habits.
Practicing this design with Natively
Object-oriented rounds reward talking while you write classes, which feels awkward until you practice it. Run a mock with a friend over a call and keep Natively open on your laptop: it transcribes both of you and can suggest points for the question in front of you, for example the case for composition over inheritance. If you share a screenshot of the class list you wrote, you can ask what responsibilities look misplaced. Afterwards, the transcript shows whether you asked about assigned spots before you started coding.
Questions people ask
How do you answer "design a parking lot" in an interview?
Ask whether it is an object-oriented question about one garage or a system for many, and confirm vehicle and spot sizes, assignment and payment rules. Then list classes with one job each (lot, spot, ticket, fee policy, gates), write the park and leave methods, and discuss concurrency and outages if time allows.
What classes does a parking lot design need?
Typically Vehicle, Spot, ParkingLot, Ticket, a FeePolicy that can be swapped, entry and exit gate adapters for the hardware, and a display board. Use a size field rather than a subclass per vehicle or spot type unless behavior genuinely differs, such as a spot that controls an electric charger.
How do you find the nearest free parking spot efficiently?
Keep a min-heap of free spots for each size, ordered by distance from the entrance. Parking tries the vehicle's own size first, then larger sizes, and pops the top of the first non-empty heap; leaving pushes the spot back. Both operations take logarithmic time instead of scanning every spot.
What happens to a parking system when the internet goes down?
In a good design the gates keep working because a controller inside the garage runs allocation and keeps open tickets in a local database. Events queue locally and sync to the central service when the link returns, with ticket IDs that let the server drop duplicates.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
