Design a Parking Lot
Design a multi-floor parking lot from the first question to the final extensions, using the seven-step method: requirements, classes, diagram, key code, scenarios and trade-offs.
"Design a parking lot" is probably the most famous low-level design question. It appears in interviews for freshers and for senior engineers alike, because it is small enough to finish in 45 minutes and rich enough to show how you think: you must find the classes, decide where the rules live, handle failures and talk about growth.
In this lesson we design it from start to finish with the seven-step method from Module 1: clarify, find the entities, assign responsibilities, draw the diagram, walk through the scenarios, write the key code and discuss extensions. We will also use patterns from the earlier modules, but only where the problem asks for them.
01The problem
Design a parking lot system. Vehicles enter, receive a ticket and park. When they leave, they pay according to how long they stayed.
Just one sentence. As you learnt, the first job is to turn it into clear requirements.
02Step 1: Clarify the requirements
Good questions for this problem, and the answers we will assume:
| Question | Answer we assume |
|---|---|
| How many floors does the lot have? | Several; each floor has many spots |
| Which vehicles come? | Bikes, cars and trucks |
| Are all spots the same? | No: small spots for bikes, regular for cars, large for trucks. A vehicle uses a spot of its own size |
| How is the fee calculated? | By the time parked. The rule may change, for example hourly or flat rate |
| What happens when the lot is full? | The vehicle is refused with a clear message |
| One gate or many? | Several gates may work at the same time |
| Payment, reservations, electric charging? | Out of scope for now. We will discuss them as extensions |
From these answers, our requirements are:
| Type | Requirement |
|---|---|
| Must do | A vehicle can park and receives a ticket |
| Must do | A vehicle can leave using its ticket and the fee is calculated |
| Must do | Each vehicle type needs a matching spot type |
| Must do | The pricing rule can be changed without rewriting the lot |
| Must do | A full lot refuses new vehicles clearly |
| Out of scope | Payments, reservations, EV charging, lost tickets |
03Steps 2 and 3: Entities and responsibilities
Underline the nouns: lot, floor, spot, vehicle, ticket, fee. Then ask who owns each job:
| Class | What it knows | What it does |
|---|---|---|
ParkingLot | Its floors and the active tickets | Parks a vehicle (park), lets it leave (unpark), and uses the pricing rule |
Floor | Its spots | Finds a free spot of the right type |
ParkingSpot | Its id, its type and whether it is occupied | Occupies and frees itself |
Vehicle | Its plate number and its type | Says which kind of spot it needs |
Ticket | Its id, the vehicle, the spot and the entry time | Proves where and when the vehicle parked |
PricingStrategy | The fee rule | Turns minutes parked into a fee |
A design decision worth saying aloud: Bike, Car and Truck do not need to be subclasses. They behave the same. They only differ in one piece of data, the spot size they need. A subclass per vehicle would be a hierarchy without any behaviour, which is a case of over-engineering (YAGNI). So we use an enum with a field.
Another decision: should ParkingLot be a Singleton? We could make it one, but we do not. A parking lot is an ordinary object that you create once and pass around. This keeps the code easy to test, as discussed in the Singleton lesson.
04Step 4: The class diagram
Read it from the top. A ParkingLot has many Floor objects, and each Floor has many ParkingSpot objects. A Ticket refers to the vehicle and to the spot it took. Two interfaces, PricingStrategy and SpotSelectionStrategy, are the points of change: the rule for the fee, and the rule for choosing a spot. These are exactly the places where a business will want to change behaviour (new price plans, "nearest to the gate"), so we put them behind interfaces. This is the Strategy pattern, and it keeps ParkingLot closed for modification.
05Step 6: The key code
Remember that we write only the important code. First the small types:
public enum SpotType { SMALL, REGULAR, LARGE }
public enum VehicleType {
BIKE(SpotType.SMALL),
CAR(SpotType.REGULAR),
TRUCK(SpotType.LARGE);
private final SpotType requiredSpot;
VehicleType(SpotType requiredSpot) { this.requiredSpot = requiredSpot; }
public SpotType requiredSpot() { return requiredSpot; }
}
public record Vehicle(String plate, VehicleType type) { }The spot protects its own state. Notice tryOccupy, which will matter when two gates work at once:
public class ParkingSpot {
private final String id;
private final SpotType type;
private boolean occupied;
public ParkingSpot(String id, SpotType type) {
this.id = id;
this.type = type;
}
public synchronized boolean tryOccupy() { // atomic: only one caller can win
if (occupied) return false;
occupied = true;
return true;
}
public synchronized void free() { occupied = false; }
public synchronized boolean isFree() { return !occupied; }
public String id() { return id; }
public SpotType type() { return type; }
}public class Floor {
private final List<ParkingSpot> spots;
public Floor(List<ParkingSpot> spots) {
this.spots = List.copyOf(spots);
}
public List<ParkingSpot> freeSpots(SpotType type) {
return spots.stream()
.filter(spot -> spot.type() == type && spot.isFree())
.toList();
}
}public interface PricingStrategy {
long feeInCents(long minutesParked);
}
public interface SpotSelectionStrategy {
Optional<ParkingSpot> choose(List<ParkingSpot> freeSpots);
}
public class FirstFreeSpot implements SpotSelectionStrategy {
public Optional<ParkingSpot> choose(List<ParkingSpot> freeSpots) {
return freeSpots.stream().findFirst();
}
}
public record Ticket(String id, Vehicle vehicle, ParkingSpot spot, Instant entryTime) { }And finally the heart of the design, ParkingLot:
public class ParkingLot {
private final List<Floor> floors;
private final PricingStrategy pricing;
private final SpotSelectionStrategy selection;
private final Map<String, Ticket> activeTickets = new ConcurrentHashMap<>();
public ParkingLot(List<Floor> floors, PricingStrategy pricing, SpotSelectionStrategy selection) {
this.floors = floors;
this.pricing = pricing;
this.selection = selection;
}
public Ticket park(Vehicle vehicle) {
SpotType needed = vehicle.type().requiredSpot();
for (Floor floor : floors) {
List<ParkingSpot> candidates = new ArrayList<>(floor.freeSpots(needed));
Optional<ParkingSpot> chosen;
while ((chosen = selection.choose(candidates)).isPresent()) {
ParkingSpot spot = chosen.get();
if (spot.tryOccupy()) { // atomic take
Ticket ticket = new Ticket(UUID.randomUUID().toString(),
vehicle, spot, Instant.now());
activeTickets.put(ticket.id(), ticket);
return ticket;
}
candidates.remove(spot); // another gate took it: try the next
}
}
throw new ParkingFullException("No free " + needed + " spot");
}
public long unpark(String ticketId) {
Ticket ticket = activeTickets.remove(ticketId);
if (ticket == null) {
throw new IllegalArgumentException("Unknown ticket: " + ticketId);
}
long minutes = Duration.between(ticket.entryTime(), Instant.now()).toMinutes();
ticket.spot().free();
return pricing.feeInCents(minutes);
}
}Look at what ParkingLot does not do: it does not know how a fee is calculated, how a spot is chosen, or how a spot is marked as occupied. Each of these is somebody else's job. ParkingLot only coordinates.
The pricing rules are the strategies from Module 6. For example:
public class HourlyPricing implements PricingStrategy {
private final long centsPerHour;
public HourlyPricing(long centsPerHour) { this.centsPerHour = centsPerHour; }
public long feeInCents(long minutesParked) {
long hours = Math.max(1, (minutesParked + 59) / 60); // at least one hour
return hours * centsPerHour;
}
}06Step 5: Walk through the scenarios
Now we test the design against real situations, the step most people skip.
Scenario A: a car enters. park asks each floor for free REGULAR spots. The selection strategy picks one. tryOccupy takes it. A ticket is created and stored. ✔ Every step uses a method on the diagram.
Scenario B: the lot is full for trucks. No floor has a free LARGE spot, so the loop ends and ParkingFullException is thrown with a clear message. ✔
Scenario C: a car leaves. unpark removes the ticket (an unknown ticket gives a clear error), calculates the minutes, frees the spot, and returns the fee from the strategy. ✔ Note that the spot is freed, so the next vehicle can use it. Forgetting this is a classic bug.
Scenario D: two gates at the same moment. Both read the same free spot. Only one tryOccupy returns true. The other call fails, removes that spot from its candidates and tries the next one. ✔ This is why occupying is atomic.
07Step 7: Extensions and trade-offs
Good designs survive new requirements. Here is how this one handles likely follow-up questions:
| New requirement | What changes |
|---|---|
| Electric vehicle charging spots | Add EV to SpotType and a ELECTRIC_CAR vehicle type that needs it. No other class changes |
| Different prices per vehicle type | Change PricingStrategy to receive the vehicle type too, or create one strategy per type |
| Nearest to the entrance | Write a new SpotSelectionStrategy. ParkingLot does not change |
| Display board with free spots | Add an Observer: spots notify listeners when they are occupied or freed |
| Payment | Add a PaymentGateway interface with adapters for each provider, and call it from the exit flow |
| Lost tickets | Look up the vehicle by its plate number in a second map, and apply a fixed fee |
| Very large lots | Keep a count or a queue of free spots for each type, so you do not scan the floors every time |
Two trade-offs you can mention: tickets are kept in memory, so a restart loses them, and a real system would store them in a database. And scanning floors for each arrival is simple but slow for huge lots, which the counting idea would fix.
08Common mistakes in this interview question
- A subclass for every vehicle type with no different behaviour. Use an enum.
- Putting the fee calculation inside
TicketorParkingLot. It will change, so give it its own strategy. - Forgetting to free the spot when a vehicle leaves.
- Ignoring the full lot. Decide and say how the failure is reported.
- Making
ParkingLota Singleton "because there is one lot". It makes testing harder and gains nothing. - Ignoring concurrency when there are several gates. At least mention the race for the same spot.
- Starting to code before the requirements. Spend the first minutes asking questions.
09In the interview
- How do you handle two entry gates at the same time? Make taking a spot atomic, for example with a synchronized tryOccupy or a compare-and-set, so only one gate gets the spot and the other tries another.
- How would you add electric vehicle charging? Add a new spot type and a matching vehicle type, and a pricing strategy if charging is billed. The existing classes stay the same.
- Why not use inheritance for Bike, Car and Truck? They differ only in data, which spot size they need, so an enum with a field is simpler than a hierarchy with no different behaviour.
10Check your understanding
Quiz · 4 questions
0 of 4 answered
1. Why are Bike, Car and Truck represented by a VehicleType enum instead of three subclasses of Vehicle?
2. Which pattern from Module 6 lets the lot calculate fees in different ways?
3. Two gates call park() at the same moment and both see the same free spot. What can fix this?
4. What should happen when no floor has a free spot of the right type?