Design a Parking Lot
🅿️ What is a parking lot system? It is the software behind the gate of a parking garage. When a vehicle drives in, it finds a free spot that the vehicle fits in and prints a ticket. When the vehicle drives out, it frees the spot and works out how much the driver owes. Display boards on each floor show how many spots are still free.
The parking lot is the most common warm-up problem in low-level design interviews. It is small enough to finish in 45 minutes, but it still tests the things interviewers care about: turning a vague prompt into clear rules, picking the right classes, keeping the entry-point class thin, and leaving room for the rule that is most likely to change (pricing).
Requirements
"Design a parking lot. It has several floors and spots of different sizes. Vehicles get a ticket when they enter and pay when they leave."
That is all most interviewers say. Everything else you have to ask for. The questions below are the ones that change the design; each answer becomes a rule we will code against.
Clarifying Questions
You: What kinds of vehicles and spots are there?
Interviewer: Three of each. Vehicles are motorcycles, cars and trucks. Spots are motorcycle, compact and large. A motorcycle fits any spot, a car fits a compact or a large spot, and a truck needs a large spot.
You: When a vehicle fits several free spots, which one does it get?
Interviewer: Don't waste big spots. Give it the smallest size that fits and has a free spot anywhere in the lot. If that size is free on several floors, use the lowest floor.
You: How is the fee computed?
Interviewer: An hourly rate that depends on the vehicle: 1 for a motorcycle, 2 for a car, 4 for a truck. Every started hour counts, and every stay pays at least one hour. The business changes its prices often, though.
You: Do we take the payment too, with cards and receipts?
Interviewer: No. Just return the amount owed. Payment is another team's system.
You: Can the same vehicle enter twice without leaving?
Interviewer: No. A plate that is already inside is turned away. Once it leaves, it can come back and get a new ticket.
You: How do we know the time? Should the lot read the system clock?
Interviewer: Pass the time in with each call, in minutes. That keeps it easy to test.
You: Do several gates use the system at the same time?
Interviewer: Assume one gate for now. We may talk about more later.
The second answer matters more than it looks. "Smallest size first, then lowest floor" is a different search from "lowest floor first, then smallest size", and the tests will tell them apart. Always pin down the tie-breaking rule before you code a search.
💡 Interview tip: Ask about time early. When the interviewer lets you pass timestamps in, every method becomes a pure function of its inputs and the lot's state. That makes your own walkthrough at the end much easier, and it is how the practice tests work too.
Final Requirements
- The lot has one or more levels. Each level has a fixed number of motorcycle, compact and large spots.
- A motorcycle fits any spot. A car fits a compact or a large spot. A truck fits only a large spot.
- When a vehicle enters, it gets a spot of the smallest size that fits and is free anywhere in the lot; among equal sizes, the lowest level wins. It gets a ticket with an id, its spot and the entry time. If no spot fits, it is turned away.
- A plate that is already inside cannot enter again.
- When a vehicle leaves with its ticket, its spot becomes free and the system returns the fee: the vehicle's hourly rate times the number of started hours, with a minimum of one hour. A ticket that was never issued, or was already used, is an error.
- Anyone can ask how many spots of a given size are free on a given level (for the display boards).
- Pricing changes often, so swapping the pricing rule must not touch the rest of the system.
Out of scope
- Payment processing, receipts and refunds.
- Reservations, monthly passes and lost tickets.
- Physical hardware: barriers, cameras, plate readers.
- Several gates at the same time (we come back to this in Extensibility).
Entities and Relationships
Read the requirements again and underline the nouns. Keep the ones that hold state or enforce a rule.
- ParkingLot: the whole garage and the entry point. It owns the levels, the active tickets and the pricing rule, and it is the only class the gate talks to.
- Level: one floor. It knows which of its spots are free and hands them out.
- ParkingSpot: one place to park, with an id, a level and a size.
- Ticket: the record of one stay: who parked, where, and when they arrived. It is what the driver hands back on the way out.
- PricingStrategy: the rule that turns a ticket and an exit time into a fee. It is its own entity because requirement 7 says it will change.
Some nouns sound like classes but are not worth one:
- Vehicle is just a plate and a type. It has no behavior of its own in this problem, so the ticket stores both as fields. Making
Car,TruckandMotorcyclesubclasses would give us three classes that differ only in a rule, and we will see a cleaner place for that rule in the Implementation section. - VehicleType and SpotSize are enums: fixed lists of names.
- Fee is an integer. Gate and DisplayBoard are callers of the lot, not parts of it.
Who owns whom:
| Owner | Owns | How many |
|---|---|---|
| ParkingLot | Level | one per floor |
| Level | ParkingSpot | all spots on that floor |
| ParkingLot | Ticket | one per vehicle inside |
| Ticket | ParkingSpot (reference) | exactly one |
| ParkingLot | PricingStrategy | exactly one, swappable |
Class Design
We go top down, starting from the class the outside world calls. A good orchestrator is thin: it checks the request, asks its parts to do the work, and records the result. If you find yourself writing size rules or fee math inside it, that logic belongs somewhere else.
ParkingLot
The orchestrator. It answers the three requests from the gate and the display boards: park, leave, and count free spots.
class ParkingLot:
levels: List[Level] # requirement 1
pricing: PricingStrategy # requirement 7: injected, so it can be swapped
active: Dict[int, Ticket] # ticket id -> ticket, vehicles still inside
plates_inside: Set[str] # requirement 4
next_ticket_id: int
def __init__(self, levels: List[List[int]], pricing: Optional[PricingStrategy] = None): ...
def park(self, plate: str, vehicle_type: str, timestamp: int) -> int: ... # ticket id or -1
def leave(self, ticket_id: int, timestamp: int) -> int: ... # fee or -1
def free_spots(self, level: int, spot_size: str) -> int: ...
active is keyed by ticket id because the exit gate only has the ticket in hand. plates_inside is a separate set so the duplicate check in park is one lookup instead of a scan over all tickets. The constructor takes plain counts per level ([motorcycle, compact, large]), which is how the practice tests build the lot.
Level
One floor. Its job is to hand out a free spot of a requested size and take it back later.
class Level:
number: int
free: Dict[SpotSize, List[ParkingSpot]] # free spots, grouped by size
def take_spot(self, size: SpotSize) -> Optional[ParkingSpot]: ...
def release(self, spot: ParkingSpot) -> None: ...
def free_count(self, size: SpotSize) -> int: ...
Grouping free spots by size is the key choice here (requirement 3 and 6). It makes both "give me a compact spot" and "how many compact spots are free?" instant. We compare it with the simpler alternative below.
ParkingSpot
@dataclass
class ParkingSpot:
spot_id: str # "L1-COMPACT-0", printed on the ticket
level: int # which Level to return it to
size: SpotSize
A spot is a small value object. It does not track whether it is occupied: a spot is free exactly when it sits in its level's free list. Keeping that fact in one place means it can never get out of sync.
Ticket
@dataclass
class Ticket:
ticket_id: int
plate: str
vehicle_type: VehicleType # the fee depends on it (requirement 5)
spot: ParkingSpot # which spot to free on exit
entry_time: int # minutes
The ticket holds everything leave needs, so leaving never has to search the lot. It also stores the vehicle type, because the price depends on the vehicle, not on the spot it ended up in: a motorcycle in a large spot still pays the motorcycle rate.
PricingStrategy
class PricingStrategy:
def fee(self, ticket: Ticket, exit_time: int) -> int: ...
class HourlyPricing(PricingStrategy):
RATES: Dict[VehicleType, int] # 1, 2, 4 per started hour
def fee(self, ticket: Ticket, exit_time: int) -> int: ...
A one-method interface with one implementation today. It is there for requirement 7 only, and the interviewer told us that rule will change, so this is one of the few places where an interface earns its keep up front.
Finally, the two enums every class above refers to. The fit rule that connects them comes in the Implementation section.
class VehicleType(Enum):
MOTORCYCLE = "MOTORCYCLE"
CAR = "CAR"
TRUCK = "TRUCK"
class SpotSize(Enum):
MOTORCYCLE = "MOTORCYCLE"
COMPACT = "COMPACT"
LARGE = "LARGE"
Implementation
We write the methods in the order a vehicle uses them: park, then leave. For each one, the happy path comes first, then the choices that matter, then the edge cases.
Parking a vehicle
Here is the whole method. It reads almost like the requirement.
def park(self, plate: str, vehicle_type: str, timestamp: int) -> int:
if plate in self.plates_inside: # requirement 4
return -1
vtype = VehicleType(vehicle_type)
spot = self._find_spot(vtype) # requirements 2 and 3
if spot is None:
return -1
ticket = Ticket(self.next_ticket_id, plate, vtype, spot, timestamp)
self.next_ticket_id += 1
self.active[ticket.ticket_id] = ticket
self.plates_inside.add(plate)
return ticket.ticket_id
Notice that the ticket id only moves forward after a spot was found. A turned-away car does not use up an id, so ids stay 1, 2, 3, ... in the order of successful entries.
All the interesting work hides in _find_spot, and it needs two answers: which spot sizes does this vehicle fit, and how do we find a free spot of a size quickly?
Bad Solution: if/else on the vehicle type
Approach
Write the fit rule as a chain of conditions inside the lot, and loop over sizes in a fixed order.
def _fits(self, vehicle_type: str, size: str) -> bool:
if vehicle_type == "MOTORCYCLE":
return True
if vehicle_type == "CAR":
return size in ("COMPACT", "LARGE")
if vehicle_type == "TRUCK":
return size == "LARGE"
return False
def _find_spot(self, vehicle_type: str) -> Optional[ParkingSpot]:
for size in ("MOTORCYCLE", "COMPACT", "LARGE"): # smallest first
if self._fits(vehicle_type, size):
for level in self.levels:
spot = level.take_spot(size)
if spot is not None:
return spot
return None
Challenges
It works, and in a rush it is a fine first draft. But the rule is spread over two places: _fits says what fits, and the tuple in _find_spot says in which order to try. Adding an electric car means editing both and hoping they agree. The raw strings also mean a typo like "COMPAT" silently fits nothing.
Good Solution: a Vehicle class per type
Approach
The classic object-oriented answer: an abstract Vehicle with a can_fit method, and one subclass per type.
class Vehicle(ABC):
def __init__(self, plate: str):
self.plate = plate
@abstractmethod
def can_fit(self, size: SpotSize) -> bool: ...
class Car(Vehicle):
def can_fit(self, size: SpotSize) -> bool:
return size in (SpotSize.COMPACT, SpotSize.LARGE)
class Truck(Vehicle):
def can_fit(self, size: SpotSize) -> bool:
return size == SpotSize.LARGE
Challenges
The rule now lives with the vehicle, which is better than a type switch in the lot. But each subclass holds a single line of logic and no state of its own, the order of sizes still lives in the lot, and the gate has to turn "CAR" into a Car object, which usually brings in a small factory. That is three classes plus a factory to express a table with three rows. If your interviewer is a stickler for inheritance this is acceptable, but it is more code than the problem needs.
Great Solution: a fit table
Approach
Write the rule down as data. For each vehicle type, list the spot sizes it fits, smallest first. The list is both the fit rule and the search order.
FITS: Dict[VehicleType, List[SpotSize]] = {
VehicleType.MOTORCYCLE: [SpotSize.MOTORCYCLE, SpotSize.COMPACT, SpotSize.LARGE],
VehicleType.CAR: [SpotSize.COMPACT, SpotSize.LARGE],
VehicleType.TRUCK: [SpotSize.LARGE],
}
def _find_spot(self, vtype: VehicleType) -> Optional[ParkingSpot]:
# Smallest fitting size first (anywhere in the lot), then the lowest level.
for size in FITS[vtype]:
for level in self.levels:
spot = level.take_spot(size)
if spot is not None:
return spot
return None
Challenges
Very few. The rule sits in one place, an interviewer can read it at a glance, and a new vehicle type is one new enum value plus one new row. The loop order is the tie-breaking rule from requirement 3: the outer loop is over sizes, the inner loop over levels. Swap the two loops and you get "lowest floor first", which is a different (and also reasonable) policy, so say out loud which one you chose and why.
The table stops being enough when vehicles grow real behavior, for example an electric car that starts a charging session when it parks. At that point a Vehicle class has a reason to exist, and you can introduce it then.
⚠️ Common mistake: Reaching for inheritance because the prompt lists "types of things". Ask what differs between the types. If the answer is a value or a short list, a table or an enum is the simpler model. Save subclasses for types that behave differently.
Finding a free spot quickly
The fit table tells us which sizes to try. Now Level.take_spot(size) has to find a free spot of one size on one floor.
Bad Solution: scan every spot
Approach
Keep one list of spots per level, each with an occupied flag, and walk the list.
class Level:
def __init__(self, spots: List[ParkingSpot]):
self.spots = spots # each spot has .size and .occupied
def take_spot(self, size: SpotSize) -> Optional[ParkingSpot]:
for spot in self.spots:
if spot.size == size and not spot.occupied:
spot.occupied = True
return spot
return None
def free_count(self, size: SpotSize) -> int:
return sum(1 for s in self.spots if s.size == size and not s.occupied)
Challenges
Every call walks the whole floor. One park call may scan every spot in the lot several times (once per fitting size), and the display boards call free_count constantly, which also scans everything. For a garage with a few hundred spots that is still fast, so this is not wrong, but the interviewer will ask what it costs, and the honest answer is "linear in the number of spots, for every request".
Good Solution: free lists by size
Approach
Each level keeps its free spots grouped by size. Taking a spot is a pop, returning one is an append, and counting is the length of a list.
class Level:
def __init__(self, number: int, counts: Dict[SpotSize, int]):
self.number = number
self.free: Dict[SpotSize, List[ParkingSpot]] = {}
for size, count in counts.items():
self.free[size] = [ParkingSpot(f"L{number}-{size.value}-{i}", number, size)
for i in range(count)]
def take_spot(self, size: SpotSize) -> Optional[ParkingSpot]:
if not self.free[size]:
return None
return self.free[size].pop()
def release(self, spot: ParkingSpot) -> None:
self.free[spot.size].append(spot)
def free_count(self, size: SpotSize) -> int:
return len(self.free[size])
Challenges
take_spot, release and free_count are all constant time, so park costs at most (number of sizes) × (number of levels) quick checks, and the boards are free. The trade-off is that a spot's state lives in the list it sits in, so we must never forget to put a spot back on exit. That is one line in leave, and the tests check it. This version is also the shape that grows best: if spots later need an order (closest to the elevator first), the list becomes a heap and nothing outside Level changes.
A Great option is not needed here. You could keep a lot-wide index of "levels that have a free compact spot" to skip full floors, but with a handful of levels that saves nothing and adds a second structure to keep in sync.
Leaving and paying
Leaving is the mirror of parking: find the ticket, free the spot, compute the fee.
def leave(self, ticket_id: int, timestamp: int) -> int:
ticket = self.active.pop(ticket_id, None)
if ticket is None:
return -1 # unknown ticket, or this vehicle already left
self.levels[ticket.spot.level].release(ticket.spot)
self.plates_inside.discard(ticket.plate)
return self.pricing.fee(ticket, timestamp)
Popping the ticket out of active does two things at once: it finds the ticket, and it makes sure the same ticket cannot be used twice. The only open question is where the fee math lives.
Bad Solution: fee math inside leave
Approach
Compute the fee right where we need it.
RATES = {VehicleType.MOTORCYCLE: 1, VehicleType.CAR: 2, VehicleType.TRUCK: 4}
def leave(self, ticket_id: int, timestamp: int) -> int:
...
minutes = timestamp - ticket.entry_time
hours = max(1, (minutes + 59) // 60)
return hours * RATES[ticket.vehicle_type]
Challenges
It is short and correct for today's rule. The trouble is requirement 7. "Free for the first 15 minutes", "half price at night" or "a daily maximum" all become if branches inside leave, the method that also frees spots and checks tickets. You also cannot test the pricing on its own without parking a car first.
Good Solution: a pricing strategy
Approach
Move the rule behind a one-method interface and hand the lot an instance. This is the Strategy pattern: the lot knows that a fee is computed, not how.
class PricingStrategy:
def fee(self, ticket: Ticket, exit_time: int) -> int:
raise NotImplementedError
class HourlyPricing(PricingStrategy):
RATES = {VehicleType.MOTORCYCLE: 1, VehicleType.CAR: 2, VehicleType.TRUCK: 4}
def fee(self, ticket: Ticket, exit_time: int) -> int:
minutes = exit_time - ticket.entry_time
hours = max(1, (minutes + 59) // 60) # round up to whole hours
return hours * self.RATES[ticket.vehicle_type]
Challenges
One extra class. In exchange, a new pricing rule is a new class passed to the constructor, leave never changes, and each pricing class can be tested with a hand-built ticket. (minutes + 59) // 60 is integer ceiling division: 60 minutes is 1 hour, 61 minutes is 2. The max(1, ...) gives the one-hour minimum, so a car that turns around at the barrier still pays for an hour. See /low-level-design/strategy-pattern for the pattern on its own.
💡 Interview tip: Use the Strategy pattern where the interviewer has told you a rule will change, and nowhere else. Here that is pricing. Wrapping the fit table or the spot search in strategies too would be over-engineering, and a good interviewer will notice.
Edge cases
Walk through these out loud before you say you are done. Each one maps to a check that is already in the code:
- Lot full for this vehicle:
_find_spotreturnsNoneandparkreturns-1. No ticket id is used. - Plate already inside: rejected before searching, so a duplicate never takes a spot.
- Unknown ticket or second exit:
active.pop(ticket_id, None)returnsNone, soleavereturns-1and frees nothing. - Zero-minute stay:
(0 + 59) // 60is 0, andmax(1, 0)charges the one-hour minimum. - Small vehicle in a big spot: a motorcycle in a large spot pays the motorcycle rate, because the fee reads
ticket.vehicle_type, not the spot size. - Spot goes back to the right floor:
releaseusesticket.spot.level, so a freed spot reappears on its own level's board.
Verification
Let's trace a small lot: level 0 has 1 motorcycle spot and 1 compact spot, level 1 has 1 compact spot and 1 large spot. This is the same sequence as the first practice test.
| # | Call | What happens | Returns |
|---|---|---|---|
| 1 | park("BIKE-1", "MOTORCYCLE", 0) |
Smallest fit is MOTORCYCLE; level 0 has one | 1 |
| 2 | park("CAR-1", "CAR", 10) |
COMPACT on level 0 | 2 |
| 3 | park("CAR-2", "CAR", 20) |
Level 0 has no compact left; COMPACT on level 1 | 3 |
| 4 | park("CAR-3", "CAR", 30) |
No COMPACT anywhere; next size LARGE, level 1 | 4 |
| 5 | park("TRUCK-1", "TRUCK", 40) |
Only LARGE fits, and it is taken | -1 |
| 6 | free_spots(1, "LARGE") |
Level 1's large list is empty | 0 |
| 7 | leave(2, 75) |
65 minutes: 2 started hours × 2 | 4 |
| 8 | leave(4, 90) |
60 minutes: 1 hour × 2; large spot on level 1 is free again | 2 |
| 9 | park("TRUCK-1", "TRUCK", 95) |
LARGE on level 1; next id is 5 (step 5 used none) | 5 |
| 10 | leave(4, 100) |
Ticket 4 is no longer in active |
-1 |
| 11 | free_spots(0, "COMPACT") |
Step 7 put the compact spot back on level 0 | 1 |
Step 4 shows the cost of the best-fit rule: a car took the only large spot, and the truck had to wait. That is a trade-off worth naming. An interviewer may ask whether cars should ever take large spots; with the fit table, the answer is a one-row change.
Complete Code
Here is the full design in each language, the same code the practice tests run against.
from dataclasses import dataclass
from enum import Enum
from typing import Dict, List, Optional, Set
class VehicleType(Enum):
MOTORCYCLE = "MOTORCYCLE"
CAR = "CAR"
TRUCK = "TRUCK"
class SpotSize(Enum):
MOTORCYCLE = "MOTORCYCLE"
COMPACT = "COMPACT"
LARGE = "LARGE"
# The spot sizes each vehicle fits, smallest first: we always try the smallest size that fits.
FITS: Dict[VehicleType, List[SpotSize]] = {
VehicleType.MOTORCYCLE: [SpotSize.MOTORCYCLE, SpotSize.COMPACT, SpotSize.LARGE],
VehicleType.CAR: [SpotSize.COMPACT, SpotSize.LARGE],
VehicleType.TRUCK: [SpotSize.LARGE],
}
@dataclass
class ParkingSpot:
spot_id: str # e.g. "L1-COMPACT-0"
level: int
size: SpotSize
@dataclass
class Ticket:
ticket_id: int
plate: str
vehicle_type: VehicleType
spot: ParkingSpot
entry_time: int # minutes
class Level:
"""One floor: keeps its free spots grouped by size, so finding one is a pop."""
def __init__(self, number: int, counts: Dict[SpotSize, int]):
self.number = number
self.free: Dict[SpotSize, List[ParkingSpot]] = {}
for size, count in counts.items():
self.free[size] = [ParkingSpot(f"L{number}-{size.value}-{i}", number, size) for i in range(count)]
def take_spot(self, size: SpotSize) -> Optional[ParkingSpot]:
if not self.free[size]:
return None
return self.free[size].pop()
def release(self, spot: ParkingSpot) -> None:
self.free[spot.size].append(spot)
def free_count(self, size: SpotSize) -> int:
return len(self.free[size])
class PricingStrategy:
def fee(self, ticket: Ticket, exit_time: int) -> int:
raise NotImplementedError
class HourlyPricing(PricingStrategy):
"""A rate per started hour, by vehicle type; every stay pays at least one hour."""
RATES = {VehicleType.MOTORCYCLE: 1, VehicleType.CAR: 2, VehicleType.TRUCK: 4}
def fee(self, ticket: Ticket, exit_time: int) -> int:
minutes = exit_time - ticket.entry_time
hours = max(1, (minutes + 59) // 60) # round up to whole hours
return hours * self.RATES[ticket.vehicle_type]
class ParkingLot:
def __init__(self, levels: List[List[int]], pricing: Optional[PricingStrategy] = None):
sizes = list(SpotSize) # MOTORCYCLE, COMPACT, LARGE: the order of the counts
self.levels = [Level(i, dict(zip(sizes, counts))) for i, counts in enumerate(levels)]
self.pricing = pricing or HourlyPricing()
self.active: Dict[int, Ticket] = {} # ticket id -> ticket, for cars still inside
self.plates_inside: Set[str] = set()
self.next_ticket_id = 1
def park(self, plate: str, vehicle_type: str, timestamp: int) -> int:
if plate in self.plates_inside:
return -1
vtype = VehicleType(vehicle_type)
spot = self._find_spot(vtype)
if spot is None:
return -1
ticket = Ticket(self.next_ticket_id, plate, vtype, spot, timestamp)
self.next_ticket_id += 1
self.active[ticket.ticket_id] = ticket
self.plates_inside.add(plate)
return ticket.ticket_id
def leave(self, ticket_id: int, timestamp: int) -> int:
ticket = self.active.pop(ticket_id, None)
if ticket is None:
return -1 # unknown ticket, or this car already left
self.levels[ticket.spot.level].release(ticket.spot)
self.plates_inside.discard(ticket.plate)
return self.pricing.fee(ticket, timestamp)
def free_spots(self, level: int, spot_size: str) -> int:
return self.levels[level].free_count(SpotSize(spot_size))
def _find_spot(self, vtype: VehicleType) -> Optional[ParkingSpot]:
# Smallest fitting size first (anywhere in the lot), then the lowest level.
for size in FITS[vtype]:
for level in self.levels:
spot = level.take_spot(size)
if spot is not None:
return spot
return None
Try it yourself: the Practice button above runs your code against the same interface.
Extensibility
These are the follow-ups interviewers ask most once the base design works. A good answer names the classes that change and, just as important, the ones that do not.
1) How would you add electric cars with charging spots?
Electric cars should prefer a charging spot, but may use a normal one when the chargers are full. This is a new vehicle type and a new spot size, and both live in the enums and the fit table.
class VehicleType(Enum):
...
ELECTRIC = "ELECTRIC"
class SpotSize(Enum):
...
CHARGING = "CHARGING"
FITS[VehicleType.ELECTRIC] = [SpotSize.CHARGING, SpotSize.COMPACT, SpotSize.LARGE]
# Should normal cars use chargers when everything else is full? Ask, then add CHARGING at the end of FITS[CAR] or not.
Level already groups spots by any size, park and leave do not change, and HourlyPricing needs a rate for the new type. If charging is billed per kilowatt-hour, that becomes a new pricing strategy.
A harder variant is a bus that needs several adjacent large spots. Free lists do not know which spots are next to each other, so Level would keep its large spots in a row and search for a run of free ones. That change still stays inside Level, which is a good sign that the boundaries are right.
2) How would you support new pricing rules?
Each rule is a new PricingStrategy. Rules that adjust another rule, like a grace period or a daily cap, can wrap an existing strategy instead of copying it.
class GracePeriodPricing(PricingStrategy):
"""Free for short stays, otherwise the wrapped rule."""
def __init__(self, inner: PricingStrategy, grace_minutes: int = 15):
self.inner = inner
self.grace_minutes = grace_minutes
def fee(self, ticket: Ticket, exit_time: int) -> int:
if exit_time - ticket.entry_time <= self.grace_minutes:
return 0
return self.inner.fee(ticket, exit_time)
lot = ParkingLot(levels, pricing=GracePeriodPricing(HourlyPricing()))
Wrapping one object in another with the same interface is the Decorator pattern. It lets you stack rules (grace period on top of a daily cap on top of hourly rates) without a class for every combination. ParkingLot does not change at all. If the rule needs new information, such as the level for "rooftop is cheaper", the ticket already carries the spot, so the strategy can read ticket.spot.level.
3) How would you give each vehicle the spot closest to the entrance?
Today take_spot returns any free spot of the right size. To prefer close spots, give each spot a distance and keep each free list as a min-heap on it.
import heapq
class Level:
def __init__(self, number: int, spots: List[ParkingSpot]):
self.free: Dict[SpotSize, List[Tuple[int, str, ParkingSpot]]] = {s: [] for s in SpotSize}
for spot in spots:
self.release(spot)
def take_spot(self, size: SpotSize) -> Optional[ParkingSpot]:
if not self.free[size]:
return None
return heapq.heappop(self.free[size])[2]
def release(self, spot: ParkingSpot) -> None:
heapq.heappush(self.free[spot.size], (spot.distance, spot.spot_id, spot))
The spot id in the tuple breaks ties so two spots at the same distance never get compared directly. Taking and releasing become O(log n), counting stays O(1), and only Level and ParkingSpot (one new distance field) change. With several entrances, the distance depends on the gate, so each level would keep one heap per entrance, or we would accept "close to the main entrance" as good enough. Ask which one the interviewer wants.
4) How would you handle several gates at the same time?
With two gates, two threads can call park at once. Both can see the last compact spot as free, and both can hand it out: a classic check-then-act race. The same race hits plates_inside and next_ticket_id. The simplest correct fix is one lock around each public method.
import threading
class ParkingLot:
def __init__(self, levels: List[List[int]], pricing: Optional[PricingStrategy] = None):
...
self._lock = threading.Lock()
def park(self, plate: str, vehicle_type: str, timestamp: int) -> int:
with self._lock:
return self._park(plate, vehicle_type, timestamp) # the code from above
def leave(self, ticket_id: int, timestamp: int) -> int:
with self._lock:
return self._leave(ticket_id, timestamp)
Each call does a few dictionary and list operations, so the lock is held for microseconds and a garage with a dozen gates never notices. Finer locks, such as one per level, sound faster, but the spot search crosses levels and park also updates lot-wide state, so you would need a careful lock order to avoid deadlock for no measurable gain. Say that trade-off out loud; it is exactly what the interviewer wants to hear. See /low-level-design/race-conditions-and-locks for the details.
💡 Interview tip: When the interviewer asks "is this thread safe?", first name the race in one sentence (two gates take the same spot), then give the simplest fix that is correct, then discuss finer-grained options. Jumping straight to per-spot locks usually adds bugs, not speed.
What is Expected at Each Level?
Junior
A junior candidate should turn the prompt into the core classes (lot, level, spot, ticket) and get park and leave working for the happy path. It is fine if the fit rule starts as an if chain and the fee math sits inside leave, as long as the code runs and the candidate can trace an example. The interviewer will help with clarifying questions and expects the candidate to handle the obvious errors (a full lot, an unknown ticket) once they are pointed out.
Mid-level
A mid-level candidate drives the requirements: asks about vehicle and spot types, the tie-breaking rule and how time is passed in, without prompting. The classes have clear jobs, the orchestrator stays thin, the fit rule lives in one place, and the pricing sits behind a strategy because the interviewer said it will change. They find the edge cases themselves (duplicate plates, second exits, the one-hour minimum) and can explain the cost of each method.
Senior
A senior candidate does all of that quickly and spends the saved time on trade-offs. They explain why Vehicle is not a class hierarchy here and when it would become one, why free lists beat scanning, and what the best-fit rule costs (cars filling large spots). On follow-ups they name exactly which class absorbs each change: chargers in the fit table, new prices as strategies or decorators, nearest spots inside Level, several gates with one lock and a clear reason not to go finer. Their design reads as small on purpose.