Tech Interview RoomStudy guides

Design & LLD

Low-level design: design a parking lot system in Java.

Advanced · 2 min read · Lesson 3 of 3 in Design & LLD

Problem

A multi-level parking lot with spots of different sizes (motorcycle, compact, large), entry and exit gates, tickets, fees by duration and vehicle type, and real-time availability. Interviewers assess object modelling, SOLID, patterns and concurrency.

Design

  • Entities: ParkingLot → Levels → ParkingSpots; Vehicle types; Ticket.
  • Strategies (open/closed): SpotAllocationStrategy (nearest first, by level, by EV charging) and PricingStrategy (hourly, flat weekend rates) are interfaces, so new policies do not change existing classes.
  • Concurrency: two cars at two gates must not get the same spot; claim a spot atomically (here with AtomicBoolean compare-and-set; in a database, a conditional update).
  • Singleton for the lot is often expected in interviews; prefer dependency injection in real code.
java
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

enum VehicleType { MOTORCYCLE, CAR, TRUCK }
enum SpotSize { SMALL, MEDIUM, LARGE }

record Vehicle(String plate, VehicleType type) {
    SpotSize requiredSize() {
        return switch (type) {
            case MOTORCYCLE -> SpotSize.SMALL;
            case CAR -> SpotSize.MEDIUM;
            case TRUCK -> SpotSize.LARGE;
        };
    }
}

final class ParkingSpot {
    final String id;
    final SpotSize size;
    private final AtomicBoolean occupied = new AtomicBoolean(false);

    ParkingSpot(String id, SpotSize size) { this.id = id; this.size = size; }
    boolean fits(Vehicle v) { return size.ordinal() >= v.requiredSize().ordinal(); }
    boolean tryOccupy() { return occupied.compareAndSet(false, true); }   // atomic claim
    void release() { occupied.set(false); }
    boolean isFree() { return !occupied.get(); }
}

record Ticket(String id, Vehicle vehicle, ParkingSpot spot, Instant entryTime) {}

interface SpotAllocationStrategy { Optional<ParkingSpot> allocate(List<ParkingSpot> spots, Vehicle v); }

/** Smallest spot that fits, so large spots stay available for trucks. */
final class BestFitStrategy implements SpotAllocationStrategy {
    public Optional<ParkingSpot> allocate(List<ParkingSpot> spots, Vehicle v) {
        for (SpotSize size : SpotSize.values()) {
            if (size.ordinal() < v.requiredSize().ordinal()) continue;
            for (ParkingSpot s : spots) if (s.size == size && s.isFree() && s.tryOccupy()) return Optional.of(s);
        }
        return Optional.empty();
    }
}

interface PricingStrategy { long feeInPaise(Ticket t, Instant exit); }

final class HourlyPricing implements PricingStrategy {
    private final Map<VehicleType, Long> ratePerHour;
    HourlyPricing(Map<VehicleType, Long> ratePerHour) { this.ratePerHour = ratePerHour; }

    public long feeInPaise(Ticket t, Instant exit) {
        long minutes = Math.max(1, Duration.between(t.entryTime(), exit).toMinutes());
        long hours = (minutes + 59) / 60;                       // round up to whole hours
        return hours * ratePerHour.get(t.vehicle().type());
    }
}

final class ParkingLot {
    private final List<ParkingSpot> spots;
    private final SpotAllocationStrategy allocation;
    private final PricingStrategy pricing;
    private final Map<String, Ticket> activeTickets = new ConcurrentHashMap<>();

    ParkingLot(List<ParkingSpot> spots, SpotAllocationStrategy allocation, PricingStrategy pricing) {
        this.spots = List.copyOf(spots);
        this.allocation = allocation;
        this.pricing = pricing;
    }

    Optional<Ticket> park(Vehicle v) {
        return allocation.allocate(spots, v).map(spot -> {
            Ticket t = new Ticket(UUID.randomUUID().toString(), v, spot, Instant.now());
            activeTickets.put(t.id(), t);
            return t;
        });
    }

    long exit(String ticketId, Instant exitTime) {
        Ticket t = activeTickets.remove(ticketId);
        if (t == null) throw new IllegalArgumentException("Unknown or already used ticket " + ticketId);
        t.spot().release();
        return pricing.feeInPaise(t, exitTime);
    }

    long freeSpots() { return spots.stream().filter(ParkingSpot::isFree).count(); }
}

class ParkingLotDemo {
    public static void main(String[] args) {
        List<ParkingSpot> spots = new ArrayList<>();
        for (int i = 0; i < 2; i++) spots.add(new ParkingSpot("S" + i, SpotSize.SMALL));
        for (int i = 0; i < 3; i++) spots.add(new ParkingSpot("M" + i, SpotSize.MEDIUM));
        spots.add(new ParkingSpot("L0", SpotSize.LARGE));

        ParkingLot lot = new ParkingLot(spots, new BestFitStrategy(),
            new HourlyPricing(Map.of(VehicleType.MOTORCYCLE, 2000L, VehicleType.CAR, 5000L, VehicleType.TRUCK, 10000L)));

        Ticket car = lot.park(new Vehicle("KA01AB1234", VehicleType.CAR)).orElseThrow();
        Ticket truck = lot.park(new Vehicle("KA02CD5678", VehicleType.TRUCK)).orElseThrow();
        System.out.println(car.spot().id + " " + truck.spot().id + " free=" + lot.freeSpots());   // M0 L0 free=4
        System.out.println(lot.park(new Vehicle("KA03EF9999", VehicleType.TRUCK)).isPresent());   // false
        long fee = lot.exit(car.id(), car.entryTime().plus(Duration.ofMinutes(130)));
        System.out.println("fee (paise) = " + fee + " free=" + lot.freeSpots());                  // 15000 free=5
    }
}

What to say about it

  • SOLID: each class has one responsibility; strategies make allocation and pricing extensible (open/closed); ParkingLot depends on interfaces (dependency inversion).
  • Money in integer paise, not double.
  • Concurrency: atomic spot claims plus a concurrent ticket map; in a real system the database enforces it (unique active ticket per spot).
  • Extensions: display boards (Observer on spot changes), payments, reservations, EV charging spots, multiple entry gates.

Follow-up questions interviewers ask

Try answering each one before you open it.

How would this change in a real distributed system with many gates?

State moves to a database: spot(id, level, size, status, version) and ticket(id, spot_id, plate, entry_time, exit_time). A gate claims a spot with a conditional update (UPDATE spot SET status='OCCUPIED' WHERE id=? AND status='FREE') or FOR UPDATE SKIP LOCKED on a free spot, and a partial unique index ensures one active ticket per spot. Availability counts per level are cached and pushed to display boards via events.

Which design patterns are used here, and where else would you add them?

Strategy (allocation, pricing), Factory (creating vehicles or spots from configuration), Singleton (one lot instance in some interview versions), Observer (notify display boards and the mobile app when availability changes), and State (a spot or ticket moving through FREE, RESERVED, OCCUPIED, OUT_OF_SERVICE).