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 Published 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

Scale if the interviewer extends it to a chain of garages (assumed figures)
QuantityAssumptionResult
Garages500 locations, about 1,000 spots each500,000 spots
Turnover3 vehicles per spot per day1.5 million tickets a day
Rate1.5 million / 86,400 secondsabout 17 entries a second on average, a few hundred at a big event's peak across the chain
Dataabout 200 bytes per ticketaround 300 MB of tickets a day
Scale if the interviewer extends it to a chain of garages (assumed figures). Scroll sideways on a small screen.

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 }
The operations the class model must support, and the matching service calls if it becomes a backend

4. Sketch the classes

Classes and what each one owns
ClassResponsibilityKey fields or methods
VehicleDescribes what arrivedplate, size
SpotA physical placeid, size, floor, distance from entrance, occupied flag
ParkingLotAllocates and frees spots; owns ticketspark, leave, free spots per size
TicketProof of entryid, spot, entered_at, paid_at
FeePolicyTurns a stay into a price; swappablefee(minutes); hourly, flat, event pricing
EntryGate / ExitGateHardware adapters: read plate or button, print ticket, open barriertalk to the lot, never decide prices themselves
DisplayBoardShows free countssubscribes to spot changes
Classes and what each one owns. Scroll sideways on a small screen.

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)
Nearest free spot of the smallest fitting size, using one heap per size; fees per started hour with a daily cap. Checked against a brute-force model.
  • 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 leave delegates to a FeePolicy object 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

  1. Devices
    • Entry and exit gates
    • Plate cameras
    • Payment terminals
    • Spot sensors
    • Display boards
  2. Garage
    • Local controller (allocation, open tickets)
    • Local database
    • Outbound event queue
  3. Central
    • Ticket and payment service
    • Pricing and passes
    • Availability API for apps
  4. Data
    • Central database
    • Reporting warehouse
Gates, local controller and a central service. Each garage has entry and exit gates with ticket printers, plate cameras and payment terminals, plus occupancy sensors over spots. They connect to a local controller in the garage, which runs the allocation logic, keeps a local database of open tickets and free spots, and drives the displays. The controller syncs tickets and events to a central service over the internet through a queue. The central service stores tickets and payments, handles monthly passes and pricing rules, sends availability to a public app, and produces reports.

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 park and leave), 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 modes worth naming
FailureEffectMitigation
Internet link downCentral service unreachableLocal controller keeps running; events queue locally and sync later
Payment terminal failsQueue at the exitAccept another method, open the barrier and bill by plate where allowed, or a staffed lane
Controller crashesGates stopRestart from the local database; a hot standby controller; manual barrier override
Sensor reports wrong stateDisplay shows spaces that do not existCross-check with ticket counts; flag sensors that disagree for maintenance
Event day rushLong entry queuePre-paid event tickets read by plate camera; open all lanes as entries
Failure modes worth naming. Scroll sideways on a small screen.

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 Spot stays 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

Moving from classes to a system when asked
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 park and leave; 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.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP