A parking lot is the classic first low-level design (LLD) question. It looks easy, so interviewers use it to see how you model: whether you reach for a pile of vehicle subclasses or find the one rule that matters, whether you keep the code small, and whether it survives "now add X". This lesson designs a multi-level lot in Java, from requirements to tested code. It follows the seven steps from the LLD approach lesson.
1. Requirements and Assumptions
Ask first, then write down what you decided.
- A lot has several levels. Each level has small, medium and large spots.
- Vehicles are motorcycles, cars and trucks. A vehicle can use a spot of its own size or a bigger one.
- Park: the driver gives a plate and a vehicle type, and gets a ticket with a spot, or the request fails if nothing fits.
- Exit: the driver gives the ticket, the spot is freed, and the receipt shows the fee.
- Fee: charged per started hour by vehicle type (motorcycle $1, car $2, truck $4), and the first 15 minutes are free. Money is kept in cents.
- The same vehicle cannot be parked twice. Two entrances can work at the same time.
- Out of scope: payment, reservations, EV charging, lost tickets, display boards. Say so, and ask if the interviewer wants any of them.
| Vehicle | Small spot | Medium spot | Large spot |
|---|---|---|---|
| Motorcycle | Yes | Yes | Yes |
| Car | No | Yes | Yes |
| Truck | No | No | Yes |
2. Finding the Classes
List the nouns and verbs. The nouns are lot, level, spot, vehicle, ticket and fee. The verbs are park, exit and charge. Not every noun needs a class.
| Class | Its one job |
|---|---|
| ParkingLot | The entry point. Issues tickets, takes them back, and owns all changing state |
| Level | Holds the free spots of one floor, and hands out and takes back spots |
| Spot, Ticket, Receipt | Plain records of data that never change |
| VehicleType, SpotSize | Enums. A vehicle type knows the smallest spot it fits |
| SpotAllocator | The rule for choosing a spot |
| PricingPolicy | The rule for computing a fee |
There is no Vehicle class and no Car or Truck subclass. A car and a truck behave the same way. They differ only in size, and a difference in data belongs in an enum field. Subclasses with no behavior of their own are the most common mistake in this question.
3. The Class Diagram
classDiagram
class ParkingLot {
+park(plate, type) Ticket
+exit(ticketId) Receipt
+available(size) int
}
class Level {
+take(size) Optional~Spot~
+release(spot)
}
class SpotAllocator {
<<interface>>
+allocate(type, levels) Optional~Spot~
}
class PricingPolicy {
<<interface>>
+feeCents(type, parked) long
}
class BestFitAllocator
class HourlyPricing
class Spot {
<<record>>
+String id
+int level
+SpotSize size
}
class Ticket {
<<record>>
}
class Receipt {
<<record>>
}
class VehicleType {
<<enum>>
}
class SpotSize {
<<enum>>
}
ParkingLot "1" *-- "1..*" Level
ParkingLot --> SpotAllocator
ParkingLot --> PricingPolicy
ParkingLot ..> Ticket
ParkingLot ..> Receipt
Level "1" o-- "*" Spot
BestFitAllocator ..|> SpotAllocator
HourlyPricing ..|> PricingPolicy
Ticket --> Spot
Ticket --> VehicleType
Spot --> SpotSize
VehicleType --> SpotSize
ParkingLot owns the levels and uses two small interfaces, one for choosing a spot and one for pricing. Those are the two rules most likely to change, so each gets an interface. Everything else stays concrete.
4. The Key Decisions
- Compare sizes, not vehicle names. A vehicle fits a spot if the spot is at least its smallest size. A new "van" type is one enum line, and no
ifchain changes. - Keep free spots in one queue per size. Allocation is then one
poll, and a spot is always in exactly one place: a free queue or an active ticket. There is no "occupied" flag to keep in sync. Scanning all 1,000 spots would also be fast enough here, so the queue is chosen for the clear invariant more than for speed. - Best fit: smallest spot first. A motorcycle takes a small spot if one is free, and only then a medium or a large one. This keeps large spots for trucks, which have nowhere else to go.
- One owner for changing state. The tickets and the parked plates live only in
ParkingLot, so there is one place to lock. - Pass the clock in. The class never calls
System.currentTimeMillis(), so a test can move time forward by hand.
5. The Code
First the model: two enums and four small types.
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.*;
enum SpotSize { SMALL, MEDIUM, LARGE }
enum VehicleType {
MOTORCYCLE(SpotSize.SMALL), CAR(SpotSize.MEDIUM), TRUCK(SpotSize.LARGE);
private final SpotSize smallestSpot;
VehicleType(SpotSize smallestSpot) { this.smallestSpot = smallestSpot; }
SpotSize smallestSpot() { return smallestSpot; }
}
record Spot(String id, int level, SpotSize size) {}
record Ticket(String id, Spot spot, String plate, VehicleType type, Instant entry) {}
record Receipt(Ticket ticket, Instant exit, Duration parked, long feeCents) {}
class LotFullException extends RuntimeException {
LotFullException(VehicleType type) { super("No spot available for " + type); }
}
A Level keeps its free spots in a queue per size. A freed spot goes to the front, so the most recently freed spot is reused first.
final class Level {
private final int number;
private final EnumMap<SpotSize, ArrayDeque<Spot>> free = new EnumMap<>(SpotSize.class);
Level(int number, int small, int medium, int large) {
this.number = number;
for (SpotSize size : SpotSize.values()) free.put(size, new ArrayDeque<>());
add(SpotSize.SMALL, small);
add(SpotSize.MEDIUM, medium);
add(SpotSize.LARGE, large);
}
private void add(SpotSize size, int count) {
if (count < 0) throw new IllegalArgumentException("Negative spot count");
for (int i = 1; i <= count; i++) {
String id = "L" + number + "-" + size.name().charAt(0) + "-" + i;
free.get(size).addLast(new Spot(id, number, size));
}
}
Optional<Spot> take(SpotSize size) { return Optional.ofNullable(free.get(size).pollFirst()); }
void release(Spot spot) { free.get(spot.size()).addFirst(spot); }
int freeCount(SpotSize size) { return free.get(size).size(); }
}
The allocator walks the sizes from the smallest that fits upward. For each size it tries the levels from the bottom floor up.
interface SpotAllocator {
Optional<Spot> allocate(VehicleType type, List<Level> levels);
}
final class BestFitAllocator implements SpotAllocator {
@Override
public Optional<Spot> allocate(VehicleType type, List<Level> levels) {
for (SpotSize size : SpotSize.values()) {
if (size.compareTo(type.smallestSpot()) < 0) continue; // too small for this vehicle
for (Level level : levels) {
Optional<Spot> spot = level.take(size);
if (spot.isPresent()) return spot;
}
}
return Optional.empty();
}
}
Pricing takes the vehicle type and the time parked. The 15-minute grace period is free, and after that every started hour counts, so 16 minutes costs one hour and 61 minutes costs two.
interface PricingPolicy {
long feeCents(VehicleType type, Duration parked);
}
final class HourlyPricing implements PricingPolicy {
private final Map<VehicleType, Long> centsPerHour;
private final Duration grace;
HourlyPricing(Map<VehicleType, Long> centsPerHour, Duration grace) {
this.centsPerHour = Map.copyOf(centsPerHour);
this.grace = grace;
}
@Override
public long feeCents(VehicleType type, Duration parked) {
if (parked.compareTo(grace) <= 0) return 0;
long startedHours = (parked.getSeconds() + 3599) / 3600;
return startedHours * centsPerHour.get(type);
}
}
ParkingLot ties it together. Both public methods are synchronized, which is explained in section 8.
final class ParkingLot {
private final List<Level> levels;
private final SpotAllocator allocator;
private final PricingPolicy pricing;
private final Clock clock;
private final Map<String, Ticket> active = new HashMap<>();
private final Set<String> parkedPlates = new HashSet<>();
private long lastTicketNumber = 0;
ParkingLot(List<Level> levels, SpotAllocator allocator, PricingPolicy pricing, Clock clock) {
this.levels = List.copyOf(levels);
this.allocator = allocator;
this.pricing = pricing;
this.clock = clock;
}
synchronized Ticket park(String plate, VehicleType type) {
Objects.requireNonNull(plate, "plate");
Objects.requireNonNull(type, "type");
if (parkedPlates.contains(plate)) {
throw new IllegalStateException("Vehicle is already parked: " + plate);
}
Spot spot = allocator.allocate(type, levels).orElseThrow(() -> new LotFullException(type));
Ticket ticket = new Ticket("T" + (++lastTicketNumber), spot, plate, type, clock.instant());
active.put(ticket.id(), ticket);
parkedPlates.add(plate);
return ticket;
}
synchronized Receipt exit(String ticketId) {
Ticket ticket = active.remove(ticketId);
if (ticket == null) {
throw new IllegalArgumentException("Unknown or already used ticket: " + ticketId);
}
parkedPlates.remove(ticket.plate());
levels.get(ticket.spot().level() - 1).release(ticket.spot());
Instant now = clock.instant();
Duration parked = Duration.between(ticket.entry(), now);
return new Receipt(ticket, now, parked, pricing.feeCents(ticket.type(), parked));
}
synchronized int available(SpotSize size) {
return levels.stream().mapToInt(level -> level.freeCount(size)).sum();
}
}
6. Walking Through One Day
A lot with a single level and one spot of each size. Rates: car $2 an hour. The output below comes from running the code.
| Step | Action | Result | Free spots (S, M, L) |
|---|---|---|---|
| 1 | park M-1 (motorcycle) | L1-S-1 | S0 M1 L1 |
| 2 | park M-2 (motorcycle) | L1-M-1 | S0 M0 L1 |
| 3 | park C-1 (car) | L1-L-1 | S0 M0 L0 |
| 4 | park T-1 (truck) | No spot available for TRUCK | S0 M0 L0 |
| 5 | C-1 leaves after 2 h 10 min | fee 600 cents | S0 M0 L1 |
| 6 | park T-1 (truck) | L1-L-1 | S0 M0 L0 |
Step 2 shows best fit: the small spot is gone, so the second motorcycle takes the medium spot. In step 3 the car takes the last large spot, which is why step 4 fails for the truck. In step 5, 2 hours 10 minutes is 3 started hours, so the fee is 3 × 200 = 600 cents, $6.00. The freed spot in step 6 goes straight to the truck.
7. Errors and Edge Cases
- Lot full:
LotFullException. It is full for that vehicle: a truck is refused when only small and medium spots are free. - Bad ticket: an unknown ticket, or one already used, throws
IllegalArgumentException. A second exit with the same ticket must not free a spot twice. - Duplicate plate: a vehicle that is already inside throws
IllegalStateException. - Null arguments are rejected at the door.
- The boundaries of the fee: exactly 15 minutes is free, 16 minutes is one hour, 60 minutes is one hour, and 61 minutes is two.
- A clock that moves backwards gives a negative duration, which this code prices at 0. A production system would reject it.
- Money as
longcents, neverdouble, so totals are exact.
8. Thread Safety
Two entrances can call park at the same moment. Without a lock, both could take the same spot from the queue, or corrupt the HashMap. The simplest correct fix is to make park and exit synchronized.
Is one lock too slow? A 1,000-spot lot that turns over 5 times a day sees 5,000 entries a day. That is 5,000 ÷ 86,400 = 0.06 entries a second, and about 0.23 at a peak of 4 times. Each call takes microseconds, so the lock is almost never contended. Finer locking (one lock per level) adds complexity for no gain here. Say that, and mention it as the next step if the interviewer pushes on scale.
9. Testing
The tests use JUnit 5. A small mutable clock replaces real time, so the fee tests run instantly.
class MutableClock extends Clock {
private Instant now = Instant.parse("2026-01-01T09:00:00Z");
void advance(Duration d) { now = now.plus(d); }
@Override public Instant instant() { return now; }
@Override public ZoneId getZone() { return ZoneOffset.UTC; }
@Override public Clock withZone(ZoneId zone) { return this; }
}
class ParkingLotTest {
private final MutableClock clock = new MutableClock();
private ParkingLot lot(int small, int medium, int large) {
var rates = Map.of(VehicleType.MOTORCYCLE, 100L, VehicleType.CAR, 200L, VehicleType.TRUCK, 400L);
return new ParkingLot(List.of(new Level(1, small, medium, large)),
new BestFitAllocator(), new HourlyPricing(rates, Duration.ofMinutes(15)), clock);
}
@Test
void motorcycleTakesSmallestSpotThatFits() {
var lot = lot(1, 1, 1);
assertEquals(SpotSize.SMALL, lot.park("M-1", VehicleType.MOTORCYCLE).spot().size());
assertEquals(SpotSize.MEDIUM, lot.park("M-2", VehicleType.MOTORCYCLE).spot().size());
assertEquals(SpotSize.LARGE, lot.park("M-3", VehicleType.MOTORCYCLE).spot().size());
assertThrows(LotFullException.class, () -> lot.park("M-4", VehicleType.MOTORCYCLE));
}
private long feeAfter(int minutes) {
var lot = lot(0, 1, 0);
var ticket = lot.park("C-1", VehicleType.CAR);
clock.advance(Duration.ofMinutes(minutes));
return lot.exit(ticket.id()).feeCents();
}
@Test
void feeChargesStartedHoursAfterTheGracePeriod() {
assertEquals(0, feeAfter(15)); // inside the 15-minute grace period
assertEquals(200, feeAfter(16)); // one started hour
assertEquals(200, feeAfter(60)); // exactly one hour
assertEquals(400, feeAfter(61)); // two started hours
}
@Test
void concurrentEntrancesNeverShareASpot() throws Exception {
var pool = Executors.newFixedThreadPool(16);
for (int round = 0; round < 300; round++) {
var lot = lot(0, 10, 0);
var start = new CountDownLatch(1);
List<Future<Ticket>> results = new ArrayList<>();
for (int i = 0; i < 32; i++) {
String plate = "C-" + i;
results.add(pool.submit(() -> {
start.await(); // all entrances arrive at the same moment
try { return lot.park(plate, VehicleType.CAR); }
catch (LotFullException e) { return null; }
}));
}
start.countDown();
Set<String> spots = new HashSet<>();
int parked = 0;
for (var f : results) {
Ticket t = f.get();
if (t != null) { parked++; spots.add(t.spot().id()); }
}
assertEquals(10, parked); // exactly 10 cars got in
assertEquals(10, spots.size()); // and each has its own spot
}
pool.shutdown();
}
}
The test file also covers: a truck is never given a small or medium spot, an exit frees the spot for reuse, a ticket cannot be used twice, and the same plate cannot park twice. The concurrency test releases 32 threads at once against 10 spots, 300 times over. In my run, with the synchronized keywords removed, this test did not finish, and with them it passes every time. A race is not guaranteed to show up in a test, so treat this as evidence and not proof.
10. Extensions the Interviewer May Ask
- EV charging or accessible spots: give
Spota feature, and let the allocator pick only spots that have the feature the vehicle needs. Pricing and tickets stay as they are. - Nearest spot to an entrance: a new
SpotAllocatorthat takes the entrance and the distance of each spot. This is why allocation is an interface. - Daily cap or evening rates: a new
PricingPolicy. The ticket already has the entry time, and the exit time is available. - Pay before exit: give the ticket a state, active, then paid, then exited, and let
exitaccept only a paid ticket (see the State pattern lesson). - Lost ticket: look up the active ticket by plate. Keep a map from plate to ticket instead of a set of plates, and charge a flat or daily fee.
- Display board: notify listeners when a spot is taken or freed (see the Observer lesson).
- Spot out of service: add
Level.disable(spot)that removes it from the free queue. - A chain of lots: each lot is its own instance with its own state. Prefix ticket IDs with a lot ID. This is now a high-level design question.
11. Common Pitfalls
- A
Vehiclebase class withCar,TruckandMotorcyclethat differ only in a number. - Scanning every spot with an "occupied" flag, and letting the flag and the data drift apart.
- Using
doublefor money. - Reading
System.currentTimeMillis()inside the class, which makes the fee impossible to test. - Rates written inside
ParkingLot, so every price change edits the core class. - Handing out the internal lists of levels or tickets, so callers can change them.
- A ticket that can be used twice and frees the same spot twice.
- Ignoring two entrances, and never mentioning thread safety.
- Building every extension up front, when the question did not ask for them.
12. Interview Questions and Answers
- Why not a Vehicle class with Car and Truck subclasses? They would share the same methods and differ only in size. That is data, so an enum field is enough and adding a type is one line.
- How do you choose a spot, and how fast is it? Best fit: try the smallest size that fits, then larger ones, and take the first free spot from that size's queue. It is O(sizes × levels), which is a handful of steps, and a poll is O(1).
- How do you stop two cars getting the same spot? Make the allocate-and-record step atomic. Here
parkissynchronized, and the spot comes out of the free queue exactly once. At 0.23 entries a second at peak, the lock is never a bottleneck. - How would you add a daily maximum fee? Write a new
PricingPolicythat caps the result per day.ParkingLotdoes not change. - How do you test the fee rules? Inject a clock, advance it by hand, and test the boundaries: 15, 16, 60 and 61 minutes.
- How would you add EV spots? Add a feature to the spot, and let the allocator filter on it. Tickets, pricing and the lot stay the same.
- What changes for a chain of lots? Each lot is its own instance, ticket IDs carry a lot prefix, and state lives in a database. The design question then moves to high level.