Design a Parking Lot

0%

Editorial Solution

Requirements

Define Core Objects

Analyze Relationships

Establish Hierarchy

Vehicle Hierarchy

Enum Alignment for Size Matching

PricingStrategy Hierarchy

Design Patterns

Strategy Pattern: Pluggable Fee Calculation

Enum Size Comparison: Size Matching Without Conditionals

Composition over Inheritance: Assembling the Lot

Define Class Members (write code)

Enums and Vehicle Hierarchy

ParkingSpot

ParkingTicket

ParkingFloor

PricingStrategy

ParkingLot

Run and Test

Adhere to SOLID Guidelines

Consider Scalability and Flexibility

Thread-Safe Spot Assignment: The Core Concurrency Challenge

Evolution Path: Per-Floor Locking

Create/Explain your diagram(s)

Future improvements

Table of Contents

Requirements

Define Core Objects

Analyze Relationships

Establish Hierarchy

Vehicle Hierarchy

Enum Alignment for Size Matching

PricingStrategy Hierarchy

Design Patterns

Strategy Pattern: Pluggable Fee Calculation

Enum Size Comparison: Size Matching Without Conditionals

Composition over Inheritance: Assembling the Lot

Define Class Members (write code)

Enums and Vehicle Hierarchy

ParkingSpot

ParkingTicket

ParkingFloor

PricingStrategy

ParkingLot

Run and Test

Adhere to SOLID Guidelines

Consider Scalability and Flexibility

Thread-Safe Spot Assignment: The Core Concurrency Challenge

Evolution Path: Per-Floor Locking

Create/Explain your diagram(s)

Future improvements

A parking lot sounds simple: car drives in, parks, pays, leaves. But underneath, the system must manage multi-floor spot inventories, match vehicles to correctly sized spots, handle concurrent entry gates without double-booking, and support pluggable pricing strategies. Let's break this down.

Interview Dialogue

CandidateHow many floors and what types of parking spots should we support?
InterviewerClick to reveal answer
CandidateCan a vehicle park in a larger spot if its matching size is full?
InterviewerClick to reveal answer
CandidateShould we support multiple entry and exit gates?
InterviewerClick to reveal answer
CandidateHow is pricing calculated?
InterviewerClick to reveal answer
CandidateDo we need reservations or pre-booking?
InterviewerClick to reveal answer
Show all answers

Functional Requirements

  1. Assign Spot by Vehicle Size: The system assigns the first available parking spot that fits the vehicle type. Motorcycles fit in small spots, cars in medium spots, and trucks in large spots. A vehicle may also park in any larger spot if its matching size is unavailable.
  2. Issue Ticket on Entry: When a vehicle enters the parking lot, the system issues a ParkingTicket containing the vehicle information, assigned spot, and entry timestamp.
  3. Compute Fee on Exit: Upon exit, the system calculates the parking fee based on the duration of stay and a configurable pricing strategy (e.g., hourly rate, flat rate).
  4. Handle Lot-Full Scenario: If no suitable spot is available for the vehicle's type, the system rejects entry and signals a lot-full condition.
  5. Support Multiple Floors: The parking lot spans multiple floors, each containing a configurable mix of small, medium, and large spots.

Non-Functional Requirements

  • Thread Safety: Multiple entry gates operate simultaneously. Spot assignment must prevent double-booking, where two vehicles are assigned the same spot because two threads read it as available at the same instant.
  • Extensibility: New pricing strategies (weekend, surge, event-based) and new vehicle types (bus, electric scooter) should be addable without modifying existing classes.
  • Correctness: No sequence of public API calls should leave a spot marked available while a vehicle is assigned to it, or vice versa.

Let's walk through a vehicle arriving and see where the objects emerge naturally.

Start by scanning the requirements for nouns. "Vehicles with license plates" gives us Vehicle. "Parking spots with sizes like small, medium, large" becomes ParkingSpot. "Multiple floors" maps to ParkingFloor. "Parking ticket with entry timestamp" gives us ParkingTicket. Not every noun becomes a class. "lot-full condition" is a boolean check on the floor, not its own entity, but nouns give you the starting lineup.

A car drives up to the gate. The system needs to find a spot on the right floor, mark it as occupied, and hand back a ticket. We need a ParkingLot that knows about its floors, a ParkingFloor that holds the spots, and a ParkingSpot that tracks availability and size.

We need a Vehicle object with a license plate and a type. Motorcycles, cars, and trucks share the same interface ("what type are you?"), making an abstract Vehicle class with subclasses Car, Motorcycle, and Truck a natural fit.

The system issues a ParkingTicket recording the vehicle, spot, and entry timestamp. On exit, the ticket computes the fee and releases the spot.

Hourly rates, flat rates, and event-based pricing all calculate fees differently. Hardcoding the logic means every new pricing model requires editing ParkingLot. Instead, a PricingStrategy interface lets each model implement its own algorithm. ParkingLot delegates fee calculation to whatever strategy is injected.

Why explicit size values for compatibility? Both VehicleType and SpotType carry an explicit size field (MOTORCYCLE=1, CAR=2, TRUCK=3 and SMALL=1, MEDIUM=2, LARGE=3). The rule is: spotType.getSize() >= vehicleType.getSize(). A motorcycle fits in SMALL or larger; a truck needs LARGE. One comparison replaces a matrix of if-else checks, and unlike ordinal(), the logic survives if someone reorders or inserts new enum constants.

Why is PricingStrategy an interface? Pricing rules vary independently of the lot's structure. A mall might use hourly rates on weekdays and flat rates on weekends. Making it an interface lets you swap algorithms at runtime without touching any other class.

Key Insight

Why a separate ParkingLot class instead of combining its responsibilities into ParkingFloor? Each class should have one reason to change. If ParkingFloor handled both its own logic and ParkingLot logic, a change to either concern would risk breaking the other.

The relationships in the parking lot system look straightforward, but there are spots where it is easy to get them wrong.

Composition: ParkingLot owns ParkingFloors, ParkingFloor owns ParkingSpots

Floors are built into the lot. You cannot take a floor out and use it elsewhere. If the lot is demolished, the floors go with it. That is composition. Same for spots within a floor.

Key Insight

Why not model ParkingTicket as the owner of ParkingSpot (composition)? Because the spot belongs to the floor, not the ticket. If the ticket owned the spot, discarding the ticket after exit would destroy the spot permanently. The floor would lose a spot after every parking session until the lot had none left.

Association: ParkingTicket references Vehicle and Spot

The ticket does not own either object. The vehicle existed before the ticket was created and survives after the ticket is discarded. The spot belongs to the floor, not the ticket. Modeling this as composition would mean deleting a ticket destroys the vehicle and spot, which is clearly wrong.

Strategy: ParkingLot depends on PricingStrategy interface

ParkingLot holds a reference to the interface, not a concrete class. Swapping pricing at runtime (e.g., hourly to event pricing when a concert starts) requires changing one reference.

Inheritance: Car, Motorcycle, Truck extend abstract Vehicle

Each subclass calls super with its specific VehicleType. The system works with the Vehicle abstraction and never uses instanceof checks.

Vehicle Hierarchy

The abstract Vehicle class holds licensePlate and type. Each subclass calls the constructor with its specific VehicleType:

java
1public abstract class Vehicle {
2  private String licensePlate;
3  private VehicleType type;
4
5  public Vehicle(String licensePlate, VehicleType type) {
6    this.licensePlate = licensePlate;
7    this.type = type;
8  }
9}
10
11public class Car extends Vehicle {
12  public Car(String licensePlate) {
13    super(licensePlate, VehicleType.CAR);
14  }
15}

This prevents invalid states: you cannot create a Car with VehicleType.TRUCK. The system works with the Vehicle abstraction and never casts to a subclass.

Enum Alignment for Size Matching

The fit check is spotType.getSize() >= vehicleType.getSize(). A motorcycle (size 1) fits in SMALL (1), MEDIUM (2), or LARGE (3). A truck (size 3) only fits in LARGE (3). Because each enum constant carries an explicit size value rather than relying on declaration order, the logic survives reordering or inserting new constants.

PricingStrategy Hierarchy

HourlyPricing holds a Map<VehicleType, Double> of per-vehicle-type hourly rates. FlatRatePricing holds a single flatRate regardless of type or duration. The internal structures differ completely, so a single class with a type enum would require if-else branches inside calculateFee().

Key Insight

The explicit size field on each enum constant is more robust than relying on ordinal(). But for non-linear relationships (like handicapped spots that accept any vehicle size), even explicit sizes are not enough. An explicit Map from VehicleType to Set of SpotType is the most flexible approach: it is self-documenting, handles arbitrary compatibility rules, and survives any enum refactoring.

Let me walk through why we reach for each pattern by showing what goes wrong without it.

Strategy Pattern: Pluggable Fee Calculation

Without the Strategy pattern, fee calculation lives inside ParkingLot. You end up writing code like:

java
1// Without Strategy - hardcoded pricing in ParkingLot
2if (pricingType.equals("hourly")) {
3  return hours * getHourlyRate(vehicleType);
4} else if (pricingType.equals("flat")) {
5  return flatRate;
6} else if (pricingType.equals("event")) {
7  return eventRate;
8}
9// Every new pricing model adds another branch

Every new pricing model adds another else-if branch, and a bug in one path could affect the others. The Strategy pattern extracts each algorithm into its own class behind a common interface.

Key Insight

The Strategy pattern turns a growing if-else chain into a one-liner delegation. ParkingLot never mentions hourly, flat, or event pricing. It just calls strategy.calculateFee(). That is why adding a tenth pricing model takes five minutes instead of a risky refactor.

Enum Size Comparison: Size Matching Without Conditionals

The classic approach to vehicle-spot matching uses a nested if-else or a lookup table:

java
1// Without size comparison - verbose matching
2if (vehicle.getType() == MOTORCYCLE)
3  return spotType == SMALL || spotType == MEDIUM || spotType == LARGE;
4if (vehicle.getType() == CAR)
5  return spotType == MEDIUM || spotType == LARGE;
6if (vehicle.getType() == TRUCK)
7  return spotType == LARGE;

The explicit size field reduces it to one line: spotType.getSize() >= vehicleType.getSize(). It extends automatically when new types are added with the right size value, regardless of declaration order.

Composition over Inheritance: Assembling the Lot

Why not have ParkingLot extend ParkingFloor? A lot IS NOT a floor; it HAS floors. Inheritance would give one floor's interface and make multi-floor support awkward. Composition keeps it clean: ParkingLot holds a List<ParkingFloor>, each floor holds a List<ParkingSpot>. Want to add a rooftop floor? Create the object and add it to the list.

Common Pitfall

A common anti-pattern is putting fee calculation inside ParkingTicket or ParkingLot with a type field and switch statement. Every new pricing model then forces you to edit the same class, risking regressions in existing pricing paths. Always extract varying algorithms behind an interface.

Level Expectations

Junior: identify Strategy for pricing and explain the size-based comparison for spot matching.

Mid-level: discuss when a compatibility map is better than size comparison and propose one for non-linear spot rules.

Senior: evaluate when composition over inheritance breaks down and propose a plugin architecture for dynamically loaded pricing strategies.

Let's build the parking lot system in Java.

Enums and Vehicle Hierarchy

The explicit size fields on VehicleType and SpotType are the foundation of size-matching. Each enum constant carries a stable numeric size, so declaration order does not matter. Each Vehicle subclass hardcodes its type in the constructor, preventing mismatches.

ParkingSpot

canFit() compares explicit size values. assign() and release() are synchronized as a fine-grained safety net for future per-floor locking.

ParkingTicket

calculateFee() takes a PricingStrategy parameter rather than holding a reference to one, keeping the ticket decoupled from pricing.

ParkingFloor

PricingStrategy

ParkingLot

The entryLock (ReentrantLock) ensures only one thread assigns a spot at a time. ConcurrentHashMap supports concurrent ticket reads/writes. AtomicInteger generates unique IDs without locking.

Interview Tip

In a live interview, write ParkingLot.enter() first. It demonstrates the ReentrantLock try-finally pattern, floor iteration, and the two-layer locking design in one method. Interviewers notice candidates who show concurrency awareness unprompted.

Run and Test

Browse the complete solution code and run it. Try modifying the code to experiment with the design.

Loading editor...

Single Responsibility Principle

  • ParkingSpot manages its own availability and size compatibility.
  • ParkingFloor handles spot lookup for a single floor.
  • ParkingTicket encapsulates entry/exit data and fee delegation.
  • ParkingLot orchestrates the entry/exit flow.
  • PricingStrategy implementations compute fees.

Each class has exactly one reason to change.

Open/Closed Principle

Adding WeekendPricing requires only a new class implementing PricingStrategy. No changes to ParkingLot or existing strategies. Adding a new vehicle type requires only extending Vehicle and adding a constant to VehicleType with the right size value. The size comparison works automatically.

Interview Tip

Power phrase for OCP: 'Adding WeekendPricing is a new class, not a code change.' Then demonstrate by sketching the class signature on the whiteboard. Interviewers want to see that you can add features without touching existing classes.

Liskov Substitution Principle

All Vehicle subclasses are interchangeable wherever a Vehicle reference is expected. ParkingSpot.canFit() works uniformly across Car, Motorcycle, and Truck through the VehicleType size field. No instanceof checks, no downcasting. Similarly, all PricingStrategy implementations honor the same contract: given duration and vehicle type, return a fee.

Interface Segregation Principle

PricingStrategy has exactly one method: calculateFee(). No implementation is forced to implement unneeded methods. Implementations can be as simple as a single-line lambda.

Dependency Inversion Principle

ParkingLot depends on the PricingStrategy interface, not on concrete classes. The strategy is injected via the constructor. Testing becomes trivial: inject a mock that returns a fixed value.

Thread-Safe Spot Assignment: The Core Concurrency Challenge

This is the section an interviewer is most likely to probe, because it is where parking systems fail if designed carelessly.

The race condition, made concrete: One remaining medium spot. Gate-A and Gate-B both receive a car. Without locking, both threads find the same spot, both call assign(), and one assignment silently overwrites the other.

Two-layer defense:

  1. Coarse-grained lock (ParkingLot.enter()): The ReentrantLock ensures only one thread searches for and assigns a spot at a time.
  2. Fine-grained lock (ParkingSpot.assign()): The synchronized method provides a safety net for future per-floor locking where two vehicles target different floors simultaneously.

Why ReentrantLock? It makes evolution to per-floor locking straightforward: replace the single lock with a Map<String, ReentrantLock> keyed by floor ID.

ConcurrentHashMap for active tickets supports concurrent put/remove from multiple gates. AtomicInteger generates unique ticket IDs without any lock.

Key Insight

The two-layer locking strategy (coarse ReentrantLock on entry, fine synchronized on ParkingSpot) is defense in depth. Start with the coarse lock for simplicity, then evolve to per-floor locking for throughput. The fine-grained lock ensures correctness survives the transition.

Evolution Path: Per-Floor Locking

For higher throughput, replace the single entryLock with per-floor locks:

java
1// Per-floor locking: lock only the floor being searched
2for (ParkingFloor floor : floors) {
3  ReentrantLock floorLock = floorLocks.get(floor.getFloorId());
4  floorLock.lock();
5  try {
6    ParkingSpot spot = floor.findAvailableSpot(vehicle.getType());
7    if (spot != null && spot.assign(vehicle)) {
8      // create ticket, add to activeTickets, return
9    }
10  } finally { floorLock.unlock(); }
11}

Now vehicles targeting different floors enter concurrently. ParkingSpot's synchronized methods provide the final safety net.

Level Expectations

Junior: explain the race condition and why a single lock prevents double-booking.

Mid-level: propose per-floor locking and explain how ParkingSpot.assign() stays correct during the migration.

Senior: compare ReentrantLock vs optimistic locking with CAS on spot assignment, and discuss when per-floor locking becomes a bottleneck in airport-scale lots.

Below is the class diagram showing the parking lot system architecture.

Key points to highlight in an interview:

  • Composition arrows (ParkingLot owns ParkingFloor owns ParkingSpot) reflect physical reality.
  • ParkingTicket uses association to Vehicle and ParkingSpot; it records a relationship, not ownership.
  • The Strategy pattern decouples pricing from lot management.
  • Vehicle inheritance is genuine IS-A; the explicit size field on each enum enables the size-matching comparison.

EV Charging Spots

Introduce an ElectricSpot subclass of ParkingSpot with a ChargingStation component. The pricing strategy can include a per-kWh surcharge. This follows composition: ElectricSpot HAS-A ChargingStation.

Reservation System

Add a Reservation class that pre-allocates a spot for a time window. A background thread releases expired reservations. Reserved spots are unavailable for walk-ins but available for the reservation holder.

Dynamic Pricing Based on Occupancy

Implement a DynamicPricing strategy that adjusts rates based on occupancy (1.5x above 50%, 2x above 80%). It wraps a base PricingStrategy, forming a Decorator pattern: new DynamicPricing(new HourlyPricing(rates), lot).

Try this problem yourself

Reading a solution is not the same as producing one under interview pressure. Design it on the whiteboard and get scored feedback.


Markdown supported

0%

Editorial Solution

Requirements

Define Core Objects

Analyze Relationships

Establish Hierarchy

Vehicle Hierarchy

Enum Alignment for Size Matching

PricingStrategy Hierarchy

Design Patterns

Strategy Pattern: Pluggable Fee Calculation

Enum Size Comparison: Size Matching Without Conditionals

Composition over Inheritance: Assembling the Lot

Define Class Members (write code)

Enums and Vehicle Hierarchy

ParkingSpot

ParkingTicket

ParkingFloor

PricingStrategy

ParkingLot

Run and Test

Adhere to SOLID Guidelines

Consider Scalability and Flexibility

Thread-Safe Spot Assignment: The Core Concurrency Challenge

Evolution Path: Per-Floor Locking

Create/Explain your diagram(s)

Future improvements

Table of Contents

Requirements

Define Core Objects

Analyze Relationships

Establish Hierarchy

Vehicle Hierarchy

Enum Alignment for Size Matching

PricingStrategy Hierarchy

Design Patterns

Strategy Pattern: Pluggable Fee Calculation

Enum Size Comparison: Size Matching Without Conditionals

Composition over Inheritance: Assembling the Lot

Define Class Members (write code)

Enums and Vehicle Hierarchy

ParkingSpot

ParkingTicket

ParkingFloor

PricingStrategy

ParkingLot

Run and Test

Adhere to SOLID Guidelines

Consider Scalability and Flexibility

Thread-Safe Spot Assignment: The Core Concurrency Challenge

Evolution Path: Per-Floor Locking

Create/Explain your diagram(s)

Future improvements