
Parking Lot Low Level Design in Java: Spots, Tickets, Fees
Parking lot low level design in Java: best-fit spots, tickets, a swappable pricing strategy, real output, a Python version and interview follow-ups.
OOP in Practice · Episode 6 of 70 · Low-Level Design Problems · Intermediate · Java 21.0.13
The problem
You’re building the software for a two-floor garage, and the parking lot low level design is your job. Bikes, cars and trucks arrive. Each needs a spot it fits in, a ticket, and a fee at exit. The owner also wants a flat event-day price without a redeploy.
Your task: design the classes and write a working, in-memory parking lot in Java.
Requirements
- Three spot sizes. A vehicle may use its own size or larger, never smaller.
- Best-fit allocation: smallest free size that fits, lowest floor first.
- Entry issues a ticket; exit with it frees the spot and returns the fee.
- Hourly pricing per started hour by vehicle size, 10 free minutes.
- The pricing rule can be swapped while running.
- Reject a full lot, a duplicate plate, a reused ticket, a backwards exit time and a blank plate.
Constraints and assumptions
- Single process, in memory, no database or gate hardware.
- Times are passed in, so output is repeatable. Fees are whole rupees; payment is out of scope.
What this tests: encapsulation, polymorphism, strategy pattern, edge-case handling
A clean parking lot low level design has a ParkingLot that owns floors, active tickets and a PricingStrategy. Each ParkingSpot guards its own occupancy. Vehicles are polymorphic types that report their size, so the lot never checks vehicle type. Pricing is a swappable strategy: hourly per started hour, or a flat event-day fee.
Try it yourself first — hint
Fees change with every promotion, so give them their own object. Size rules rarely change, so a vehicle can just report its size.
Step 1: Identify the objects and responsibilities
| Class / interface | Responsibility | Key methods |
|---|---|---|
Vehicle (sealed interface) |
A plate and a size; only three permitted kinds. | plate(), size() |
Bike, Car, Truck (records) |
Immutable; reject a blank plate. | size(), label() |
Size (enum) |
SMALL, MEDIUM, LARGE and the “fits in” rule. | fitsIn() |
ParkingSpot |
The only code that marks a spot taken or free. | park(), vacate(), isFree() |
ParkingFloor |
Holds one floor’s spots; finds a free one by size. | freeSpot() |
Ticket, Receipt (records) |
What the driver gets on entry and on exit. | accessors |
PricingStrategy (interface) |
Turns a vehicle size and a stay into a fee. | fee() |
HourlyPricing, FlatRatePricing |
Two interchangeable fee rules. | fee() |
ParkingLot |
Allocation, tickets, duplicate checks, pricing. | park(), unpark(), setPricing() |
Step 2: The naive approach and why it breaks
A first attempt: one class, an array of booleans and a string for the vehicle type.
public class Naive {
public static void main(String[] args) {
ParkingLot lot = new ParkingLot();
int truckSpot = lot.park("truck"); // spot 0 is meant for bikes
int carSpot = lot.park("car");
System.out.println("truck in spot " + truckSpot + ", car in spot " + carSpot);
System.out.println("car 59 min -> fee " + lot.fee("car", 59));
System.out.println("car 121 min -> fee " + lot.fee("car", 121));
lot.occupied[1] = false; // anyone can free a spot
System.out.println("car spot free again? " + !lot.occupied[1]);
}
}
class ParkingLot {
public boolean[] occupied = new boolean[4]; // spot sizes not modelled
int park(String type) {
for (int i = 0; i < occupied.length; i++)
if (!occupied[i]) { occupied[i] = true; return i; }
return -1; // full: caller must check
}
int fee(String type, int minutes) {
int hours = minutes / 60; // truncates
if (type.equals("bike")) return hours * 20;
if (type.equals("car")) return hours * 40;
return hours * 100; // new type = edit here
}
}
Run with java Naive.java, it prints:
truck in spot 0, car in spot 1 car 59 min -> fee 0 car 121 min -> fee 80 car spot free again? true
- Sizes are not modelled. The truck takes spot 0, which was meant for bikes. Nothing stops it.
- The fee truncates.
minutes / 60is integer division, so 59 minutes is free and 121 minutes is billed as 2 hours. - State is public. Any code can write
occupied[1] = falseand free a spot with a car still in it. - Every change edits the same method. A new vehicle type or an event-day price means another branch in
fee().
Step 3: The design
+------------------------------+ +---------------------------------+
| ParkingLot | uses | <<interface>> PricingStrategy |
| - floors: List<ParkingFloor> |------->| + fee(size, stay): int |
| - active: Map<id, Ticket> | +-------^----------------^--------+
| - platesInside: Set | | |
| + park(v, at): Ticket | HourlyPricing FlatRatePricing
| + unpark(id, at): Receipt | - ratePerHour - perVisit
| + setPricing(strategy) | - graceMinutes
+--------------+---------------+
| 1..n
v
+------------------------+ 1..n +--------------------------+
| ParkingFloor |------->| ParkingSpot |
| + freeSpot(size) | | - id, size |
+------------------------+ | - parked: Vehicle (null) |
| + park(v) + vacate() |
+-----------------------------+ +--------------------------+
| <<sealed>> Vehicle |
| + plate() + size(): Size | Ticket(id, vehicle, spot, entry)
+----^---------^---------^----+ Receipt(ticketId, plate, minutes, fee)
Bike Car Truck
Three ideas carry the design.
Encapsulation at the spot. ParkingSpot keeps parked private; only park() and vacate() change it. Same guard idea as encapsulation in Python.
Polymorphism for vehicles. The lot calls v.size() and never asks “is this a truck?”, which is polymorphism in OOP. Vehicle is a sealed interface, so only permitted classes implement it.
Strategy for pricing. The Strategy pattern puts each algorithm in its own class behind one interface. ParkingLot is the context: it holds one PricingStrategy and calls fee() blind. The lot has a pricing rule, as in composition vs inheritance.
Step 4: The parking lot low level design solution in Java
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<Size, Integer> rates = Map.of(Size.SMALL, 20, Size.MEDIUM, 40, Size.LARGE, 100);
ParkingLot lot = new ParkingLot(List.of(
new ParkingFloor(0, List.of(Size.SMALL, Size.MEDIUM, Size.LARGE)),
new ParkingFloor(1, List.of(Size.MEDIUM, Size.MEDIUM))),
new HourlyPricing(rates, 10));
LocalDateTime day = LocalDateTime.of(2026, 11, 23, 9, 0);
System.out.println("== Arrivals, one every 5 minutes ==");
List<Vehicle> queue = List.of(new Bike("KA-01-B-1"), new Car("KA-02-C-2"), new Truck("KA-03-T-3"),
new Car("KA-04-C-4"), new Bike("KA-05-B-5"), new Truck("KA-06-T-6"), new Car("KA-02-C-2"));
Map<String, String> ticketOf = new HashMap<>();
int minute = 0;
for (Vehicle v : queue) {
try {
Ticket t = lot.park(v, day.plusMinutes(minute += 5));
ticketOf.put(v.plate(), t.id());
System.out.printf("%s %-5s %s -> %s%n", t.id(), v.label(), v.plate(), t.spot().id());
} catch (IllegalStateException e) {
System.out.printf("REJECTED %s %s: %s%n", v.label(), v.plate(), e.getMessage());
}
}
System.out.println("free now: " + lot.freeBySize());
System.out.println("== Exits (hourly pricing, 10 min grace) ==");
exit(lot, ticketOf.get("KA-01-B-1"), day.plusMinutes(13)); // 8 min
exit(lot, ticketOf.get("KA-02-C-2"), day.plusMinutes(131)); // 2h 1min
exit(lot, ticketOf.get("KA-03-T-3"), day.plusMinutes(75)); // exactly 1h
exit(lot, ticketOf.get("KA-01-B-1"), day.plusMinutes(30)); // reused ticket
exit(lot, ticketOf.get("KA-05-B-5"), day.plusMinutes(1)); // clock error
System.out.println("== Event day: pricing strategy swapped at run time ==");
lot.setPricing(new FlatRatePricing(150));
exit(lot, ticketOf.get("KA-04-C-4"), day.plusHours(9));
System.out.println("free now: " + lot.freeBySize());
try { new Car(" "); } catch (IllegalArgumentException e) { System.out.println("invalid vehicle: " + e.getMessage()); }
}
static void exit(ParkingLot lot, String ticketId, LocalDateTime at) {
try {
Receipt r = lot.unpark(ticketId, at);
System.out.printf("%s %s stayed %d min, pays Rs %d%n", r.ticketId(), r.plate(), r.minutes(), r.fee());
} catch (IllegalStateException e) {
System.out.println("REJECTED exit " + ticketId + ": " + e.getMessage());
}
}
}
enum Size {
SMALL(1), MEDIUM(2), LARGE(3);
private final int rank;
Size(int rank) { this.rank = rank; }
boolean fitsIn(Size spot) { return spot.rank >= rank; }
}
sealed interface Vehicle permits Bike, Car, Truck {
String plate();
Size size();
String label();
static String checked(String plate) {
if (plate == null || plate.isBlank()) throw new IllegalArgumentException("plate must not be blank");
return plate.strip();
}
}
record Bike(String plate) implements Vehicle {
Bike { plate = Vehicle.checked(plate); }
public Size size() { return Size.SMALL; } public String label() { return "bike"; }
}
record Car(String plate) implements Vehicle {
Car { plate = Vehicle.checked(plate); }
public Size size() { return Size.MEDIUM; } public String label() { return "car"; }
}
record Truck(String plate) implements Vehicle {
Truck { plate = Vehicle.checked(plate); }
public Size size() { return Size.LARGE; } public String label() { return "truck"; }
}
final class ParkingSpot {
private final String id;
private final Size size;
private Vehicle parked; // null = free
ParkingSpot(String id, Size size) { this.id = id; this.size = size; }
String id() { return id; }
Size size() { return size; }
boolean isFree() { return parked == null; }
void park(Vehicle v) {
if (!isFree() || !v.size().fitsIn(size)) throw new IllegalStateException(id + " cannot take " + v.plate());
parked = v;
}
void vacate() { parked = null; }
}
final class ParkingFloor {
private final List<ParkingSpot> spots = new ArrayList<>();
ParkingFloor(int number, List<Size> layout) {
for (int i = 0; i < layout.size(); i++) spots.add(new ParkingSpot("F" + number + "-S" + (i + 1), layout.get(i)));
}
Optional<ParkingSpot> freeSpot(Size exact) {
return spots.stream().filter(s -> s.isFree() && s.size() == exact).findFirst();
}
List<ParkingSpot> spots() { return Collections.unmodifiableList(spots); }
}
record Ticket(String id, Vehicle vehicle, ParkingSpot spot, LocalDateTime entry) {}
record Receipt(String ticketId, String plate, long minutes, int fee) {}
interface PricingStrategy { int fee(Size vehicleSize, Duration stay); }
record HourlyPricing(Map<Size, Integer> ratePerHour, int graceMinutes) implements PricingStrategy {
HourlyPricing {
if (!ratePerHour.keySet().containsAll(EnumSet.allOf(Size.class))) throw new IllegalArgumentException("rate missing");
ratePerHour = Map.copyOf(ratePerHour); // caller can't change our rates later
}
public int fee(Size size, Duration stay) {
long minutes = stay.toMinutes();
if (minutes <= graceMinutes) return 0;
long startedHours = (minutes + 59) / 60; // 61 min = 2 hours
return (int) startedHours * ratePerHour.get(size);
}
}
record FlatRatePricing(int perVisit) implements PricingStrategy {
public int fee(Size size, Duration stay) { return perVisit; }
}
final class ParkingLot {
private final List<ParkingFloor> floors;
private final Map<String, Ticket> active = new HashMap<>(); // ticket id -> ticket
private final Set<String> platesInside = new HashSet<>();
private PricingStrategy pricing;
private int nextTicket = 1001;
ParkingLot(List<ParkingFloor> floors, PricingStrategy pricing) { this.floors = List.copyOf(floors); this.pricing = pricing; }
void setPricing(PricingStrategy pricing) { this.pricing = Objects.requireNonNull(pricing); }
Ticket park(Vehicle v, LocalDateTime at) {
if (platesInside.contains(v.plate())) throw new IllegalStateException("already inside");
ParkingSpot spot = bestFit(v).orElseThrow(() -> new IllegalStateException("no free spot for a " + v.size() + " vehicle"));
spot.park(v);
Ticket t = new Ticket("T" + nextTicket++, v, spot, at);
active.put(t.id(), t);
platesInside.add(v.plate());
return t;
}
Receipt unpark(String ticketId, LocalDateTime at) {
Ticket t = active.get(ticketId);
if (t == null) throw new IllegalStateException("unknown or already used ticket");
if (at.isBefore(t.entry())) throw new IllegalStateException("exit time is before entry");
active.remove(ticketId);
t.spot().vacate();
platesInside.remove(t.vehicle().plate());
Duration stay = Duration.between(t.entry(), at);
return new Receipt(t.id(), t.vehicle().plate(), stay.toMinutes(), pricing.fee(t.vehicle().size(), stay));
}
/** Smallest spot size that fits, lowest floor first, so big spots stay free for big vehicles. */
private Optional<ParkingSpot> bestFit(Vehicle v) {
for (Size size : Size.values())
if (v.size().fitsIn(size))
for (ParkingFloor f : floors) {
Optional<ParkingSpot> s = f.freeSpot(size);
if (s.isPresent()) return s;
}
return Optional.empty();
}
Map<Size, Integer> freeBySize() {
Map<Size, Integer> free = new EnumMap<>(Size.class);
for (Size s : Size.values()) free.put(s, 0);
for (ParkingFloor f : floors) for (ParkingSpot s : f.spots()) if (s.isFree()) free.merge(s.size(), 1, Integer::sum);
return free;
}
}
- Vehicles are records. A record class has private final fields and is implicitly final. Its compact constructor validates, so a blank plate never becomes an object.
- Best fit is a loop.
Size.values()returns constants in the order they are declared, small to large; an explicitrankdrivesfitsIn(). - The spot checks again.
ParkingSpot.park()rejects a wrong size, so an allocation bug fails loudly. - Exit validates first. A bad exit time leaves the ticket usable.
- Pricing copies its input. In a separate check run, editing the caller’s rate map afterwards did not change the fee.
Step 5: Run it and check the output
== Arrivals, one every 5 minutes ==
T1001 bike KA-01-B-1 -> F0-S1
T1002 car KA-02-C-2 -> F0-S2
T1003 truck KA-03-T-3 -> F0-S3
T1004 car KA-04-C-4 -> F1-S1
T1005 bike KA-05-B-5 -> F1-S2
REJECTED truck KA-06-T-6: no free spot for a LARGE vehicle
REJECTED car KA-02-C-2: already inside
free now: {SMALL=0, MEDIUM=0, LARGE=0}
== Exits (hourly pricing, 10 min grace) ==
T1001 KA-01-B-1 stayed 8 min, pays Rs 0
T1002 KA-02-C-2 stayed 121 min, pays Rs 120
T1003 KA-03-T-3 stayed 60 min, pays Rs 100
REJECTED exit T1001: unknown or already used ticket
REJECTED exit T1005: exit time is before entry
== Event day: pricing strategy swapped at run time ==
T1004 KA-04-C-4 stayed 520 min, pays Rs 150
free now: {SMALL=1, MEDIUM=2, LARGE=1}
invalid vehicle: plate must not be blank
Tested: OpenJDK 21.0.13 — java Main.java, 2026-11-23. Output above is copied from that run.
The second bike finds no small spot and takes a medium one; trucks only get the large spot. Every invalid case is rejected, and after the swap a 520-minute stay costs the flat Rs 150. A separate assert run passed the boundaries: 10 minutes free, 11 and 60 minutes one hour, 61 minutes two.
Why this design works
- Single responsibility: spots guard occupancy, floors hold spots, pricing computes money, and the lot coordinates. See the single responsibility principle.
- Open for extension: a weekend rate is one new
PricingStrategyclass.ParkingLotdoes not change. That is the open/closed principle. - Invalid states are hard to reach: no public fields, and records reject bad plates.
- Testable: time is an argument, so tests are repeatable.
Trade-offs, edge cases and when not to use it
| Choice | Benefit | Cost or risk |
|---|---|---|
| Best-fit allocation | Large spots stay free for trucks | A bike may go upstairs past a free large spot |
Sealed Vehicle + records |
Closed set of kinds, checked by the compiler | A new kind (bus) means editing the permits list |
| Pricing as a strategy | New rules need no change to the lot | One more interface |
| Fee by vehicle size | A bike in a car spot pays the bike rate | Spot-based pricing needs another strategy |
| In-memory maps | Fast and simple | Lost on restart; one process only |
Two edge cases remain open. park() is not thread-safe, and a lost ticket needs a plate lookup plus a penalty. For a lot with one fixed price, a strategy interface is ceremony. My recommendation: add it when a second pricing rule appears.
Interview follow-up questions
How would you make park() safe with two entry gates?
The bug is check-then-act: gates A and B both see F0-S3 free and both park. In one process, the simplest fix is a lock around find-and-claim, for example synchronized park() and unpark(). That serialises entries, which is fine for one garage. For more throughput, give each spot an atomic claim and retry on failure. With a shared database, claim the spot row in the same transaction, as the two-gate race write-up on PracHub describes.
How would you add electric-vehicle charging spots?
Charging is a property of the spot, not a new vehicle kind. Add a Set<Feature> to ParkingSpot and let a vehicle request features. Then move spot selection into a SpotSelectionStrategy, the same pattern as pricing, so best fit, nearest-to-lift and EV-first become interchangeable classes. Charging fees become a PricingStrategy that wraps the hourly one and adds a per-kWh charge.
How would you unit test this design?
Test the pieces alone. Pricing tests pass fixed durations and check 10, 11, 60 and 61 minutes. Spot tests check that a small spot refuses a truck. Lot tests build a tiny lot with one spot per size, pass explicit times, and assert the best-fit choice, each rejection and the reused-ticket failure. Because time is a parameter, no test sleeps or mocks a clock.
The same solution in Python
Show the Python version
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import Enum
from typing import Protocol
class Size(Enum):
SMALL = 1
MEDIUM = 2
LARGE = 3
def fits_in(self, spot: Size) -> bool:
return spot.value >= self.value
@dataclass(frozen=True)
class Vehicle:
plate: str
size = Size.MEDIUM # class attribute, overridden below
def __post_init__(self) -> None:
if not self.plate.strip():
raise ValueError("plate must not be blank")
class Bike(Vehicle): size = Size.SMALL
class Car(Vehicle): size = Size.MEDIUM
class Truck(Vehicle): size = Size.LARGE
class Spot:
def __init__(self, spot_id: str, size: Size) -> None:
self.id, self.size, self._parked = spot_id, size, None
@property
def free(self) -> bool:
return self._parked is None
def park(self, v: Vehicle) -> None:
if not self.free or not v.size.fits_in(self.size):
raise RuntimeError(f"{self.id} cannot take {v.plate}")
self._parked = v
def vacate(self) -> None:
self._parked = None
class PricingStrategy(Protocol):
def fee(self, size: Size, stay: timedelta) -> int: ...
@dataclass(frozen=True)
class HourlyPricing:
rate: dict[Size, int]
grace_minutes: int
def fee(self, size: Size, stay: timedelta) -> int:
minutes = int(stay.total_seconds() // 60)
if minutes <= self.grace_minutes:
return 0
return -(-minutes // 60) * self.rate[size] # ceiling division
@dataclass(frozen=True)
class FlatRatePricing:
per_visit: int
def fee(self, size: Size, stay: timedelta) -> int:
return self.per_visit
@dataclass(frozen=True)
class Ticket:
id: str
vehicle: Vehicle
spot: Spot
entry: datetime
class ParkingLot:
def __init__(self, floors: list[list[Size]], pricing: PricingStrategy) -> None:
self._floors = [[Spot(f"F{n}-S{i + 1}", s) for i, s in enumerate(layout)]
for n, layout in enumerate(floors)]
self.pricing = pricing
self._active: dict[str, Ticket] = {}
self._next = 1001
def park(self, v: Vehicle, at: datetime) -> Ticket:
if any(t.vehicle.plate == v.plate for t in self._active.values()):
raise RuntimeError("already inside")
spot = next((s for size in Size if v.size.fits_in(size)
for floor in self._floors for s in floor
if s.free and s.size is size), None)
if spot is None:
raise RuntimeError(f"no free spot for a {v.size.name} vehicle")
spot.park(v)
ticket = Ticket(f"T{self._next}", v, spot, at)
self._next += 1
self._active[ticket.id] = ticket
return ticket
def unpark(self, ticket_id: str, at: datetime) -> tuple[int, int]:
t = self._active.get(ticket_id)
if t is None:
raise RuntimeError("unknown or already used ticket")
if at < t.entry:
raise RuntimeError("exit time is before entry")
del self._active[ticket_id]
t.spot.vacate()
stay = at - t.entry
return int(stay.total_seconds() // 60), self.pricing.fee(t.vehicle.size, stay)
if __name__ == "__main__":
lot = ParkingLot([[Size.SMALL, Size.MEDIUM, Size.LARGE], [Size.MEDIUM, Size.MEDIUM]],
HourlyPricing({Size.SMALL: 20, Size.MEDIUM: 40, Size.LARGE: 100}, 10))
day = datetime(2026, 11, 23, 9, 0)
tickets: dict[str, str] = {}
queue = [Bike("KA-01-B-1"), Car("KA-02-C-2"), Truck("KA-03-T-3"), Car("KA-04-C-4"),
Bike("KA-05-B-5"), Truck("KA-06-T-6"), Car("KA-02-C-2")]
for i, v in enumerate(queue, start=1):
try:
t = lot.park(v, day + timedelta(minutes=5 * i))
tickets[v.plate] = t.id
print(f"{t.id} {type(v).__name__.lower():<5} {v.plate} -> {t.spot.id}")
except RuntimeError as e:
print(f"REJECTED {type(v).__name__.lower()} {v.plate}: {e}")
for plate, minute in [("KA-01-B-1", 13), ("KA-02-C-2", 131), ("KA-03-T-3", 75), ("KA-01-B-1", 30)]:
try:
mins, fee = lot.unpark(tickets[plate], day + timedelta(minutes=minute))
print(f"{tickets[plate]} {plate} stayed {mins} min, pays Rs {fee}")
except RuntimeError as e:
print(f"REJECTED exit {tickets[plate]}: {e}")
lot.pricing = FlatRatePricing(150)
mins, fee = lot.unpark(tickets["KA-04-C-4"], day + timedelta(hours=9))
print(f"event day: {tickets['KA-04-C-4']} stayed {mins} min, pays Rs {fee}")
T1001 bike KA-01-B-1 -> F0-S1 T1002 car KA-02-C-2 -> F0-S2 T1003 truck KA-03-T-3 -> F0-S3 T1004 car KA-04-C-4 -> F1-S1 T1005 bike KA-05-B-5 -> F1-S2 REJECTED truck KA-06-T-6: no free spot for a LARGE vehicle REJECTED car KA-02-C-2: already inside T1001 KA-01-B-1 stayed 8 min, pays Rs 0 T1002 KA-02-C-2 stayed 121 min, pays Rs 120 T1003 KA-03-T-3 stayed 60 min, pays Rs 100 REJECTED exit T1001: unknown or already used ticket event day: T1004 stayed 520 min, pays Rs 150
Tested with Python 3.13.18 (python3 main.py). Vehicles are frozen dataclasses, so assigning to plate raises FrozenInstanceError. Pricing is a Protocol, matched by structural subtyping, not inheritance.
Practice: extend it yourself
- Add
WeekendPricing: half the hourly rate on Saturday and Sunday. Expected behaviour: a car parked 2h01m on a Saturday pays Rs 60;ParkingLotis unchanged. - Add
lostTicket(plate, at). Expected behaviour: it frees the plate’s spot and charges the normal fee plus Rs 200; an unknown plate is rejected. - Make
park()andunpark()thread-safe. Expected behaviour: 50 threads parking 50 cars into 10 spots produce exactly 10 tickets and 40 “no free spot” rejections.
- A parking lot low level design needs vehicles, spots, floors, tickets, pricing and a coordinating lot.
- Best fit tries the smallest fitting spot size first, keeping large spots for trucks.
- Pricing per started hour means rounding minutes up, so 61 minutes is billed as two hours.
- The Strategy pattern swaps hourly for flat pricing without changing the lot class.
- A spot that guards its own occupancy blocks a truck in a bike spot.
- Find-then-claim on a shared spot is a race; with several gates it must be one atomic step.
Frequently Asked Questions
What is parking lot low level design?
It is a classic object-oriented design practice problem. You model a multi-floor lot with classes for vehicles, spots, floors, tickets and pricing, then park vehicles in fitting spots, issue tickets and charge fees at exit. It tests encapsulation, polymorphism and clean extension points.
Which design patterns are used in a parking lot system?
Strategy is the most useful: hourly, flat event-day or weekend pricing sit behind one interface and can be swapped at run time. Spot selection can be a second strategy. Singleton is often suggested for the lot, but passing the lot in keeps code testable.
How do you calculate parking fees in a low level design?
Put the rule in a pricing class, not in the lot. A common hourly rule charges per started hour: round minutes up, so 61 minutes costs two hours. Check any grace period, such as 10 free minutes, first. Keep rates per vehicle size in a map instead of if/else branches.
How do you stop two cars getting the same parking spot?
Make finding and claiming a spot one atomic step. In one process, guard park() with a lock. With several gates and a shared database, claim the row in the same transaction that checks it, for example with SELECT … FOR UPDATE SKIP LOCKED. A separate check and write lets two gates win.
Should a bike be allowed to park in a car spot?
Usually yes, if no bike spot is free; rejecting it while car spots sit empty loses revenue. Best-fit allocation tries the smallest fitting size first, keeping large spots free for trucks. If pricing follows the vehicle, the bike still pays the bike rate.
References
- Oracle — Java SE Language Guide: Sealed Classes and Interfaces
- Oracle Java SE 21 — Record Classes
- Oracle Java Tutorials — Enum Types
- Refactoring.Guru — Strategy
- Wikipedia — Strategy pattern
- Python documentation — dataclasses
- Python typing documentation — Protocols and structural subtyping
- PracHub — Parking Lot Design Interview: the two-gate race