Notes
Requirements
Start by fixing the scope. The lot has several floors with small, medium and large spots. Motorcycles, cars and trucks arrive. The entry gate finds a spot and issues a ticket, the exit gate charges by the hour, and payment can be card, cash or UPI. Display boards show free spots per size. Several gates work at the same time. Say what is out of scope, like reservations, so the interviewer can push back early.
Ask the questions that change the code. Can a motorcycle use a car spot? Yes, smaller vehicles fit bigger spots. Can a truck span two spots? No, it needs a large one. Is pricing flat or hourly? Hourly, with a rate per spot size. What about a lost ticket? Charge a daily maximum. Each answer becomes a rule in a specific class, which is exactly what the interviewer wants to see.
- several floors, many spots
- spot sizes: small, medium, large
- vehicles: bike, car, truck
- entry gate issues a ticket
- exit gate charges by the hour
- pay by card, cash or UPI
- boards show free spots per size
- many gates work at once
- out of scope: booking ahead,
- number plate cameras
- can a bike use a car spot?
- yes: smaller fits bigger
- can a truck use two spots?
- no: trucks need large
- flat fee or hourly?
- hourly, rate per spot size
- lost ticket?
- charge the daily maximum
- one lot or many?
- one lot, many gates
Entities
Now the entities. Underline the nouns in the requirements: lot, floor, spot, vehicle, ticket. The lot has many floors, each floor has many spots, and a spot holds at most one vehicle. The lot issues a ticket that points at the vehicle, the spot and the entry time. Notice what is not a class: a gate is just a caller of the lot, so we keep it out of the model until it needs its own behaviour.
Class diagram
Turn them into types. Fixed kinds become enums: vehicle type and spot size. Things that never change after creation become Java records: a vehicle, a floor, a ticket, a receipt. Money is a long number of cents, never a double, so rounding never loses a paisa. Only one class has changing state, the spot, because it is either free or holding a vehicle. Keeping mutable state in one place makes the thread safety story short.
Where does the rule live that a car cannot use a small spot? On the spot, because the spot owns its size. A switch over the vehicle type returns true or false, and the compiler checks every enum value is covered, so adding a new vehicle type later forces you to decide its rule. Put behaviour next to the data it reads; that one habit answers most where-does-this-go questions.
enum VehicleType { MOTORCYCLE, CAR, TRUCK }
enum SpotSize { SMALL, MEDIUM, LARGE }
record Vehicle(String plate, VehicleType t)
record Floor(int number, List<Spot> spots)
record Ticket(String id, Vehicle vehicle,
Spot spot, Instant entry)
record Receipt(id, plate, stayed, fee) boolean fits(Vehicle v) {
return switch (v.type()) {
case MOTORCYCLE -> true;
case CAR -> size != SpotSize.SMALL;
case TRUCK -> size == SpotSize.LARGE;
};
} Strategy: spot choice
Which spot should a car get? That is a business policy, and policies change, so put it behind an interface: the Strategy pattern. Our default is best fit: try the smallest size that fits, lowest floor first, so large spots stay free for trucks. Tomorrow the business wants nearest to the lift, or electric charging spots first. Each is a new class, and the parking lot itself does not change. That is the open-closed principle in one sentence.
interface SpotStrategy {
List<Spot> candidates(List<Floor> f,
Vehicle v);
}
BestFitStrategy: smallest size that
fits, lowest floor first
NearestLiftStrategy, EvFirstStrategy:
new classes, ParkingLot unchanged Strategy: pricing
Pricing is the second strategy. HourlyPricing charges per started hour with a rate per spot size, so a hundred and fifty minutes on a medium spot is three hours. A weekend rate or a flat event fee is another class. Payment is a third tiny interface with one method, charge, so card, cash and UPI plug in without the lot knowing which is which. Three small interfaces beat one giant class full of if statements.
long feeCents(Ticket t, Instant exit) {
long min = max(1, between(entry, exit)
.toMinutes());
long hours = (min + 59) / 60;
return hours * centsPerHour.get(size);
}
150 minutes on a medium spot
= 3 hours x 200 = 600 cents Observer: boards
Display boards use the Observer pattern. Each board subscribes with a listener, and after every park or release the lot publishes the new free count for that size. The lot does not care whether one board or fifty are listening, or whether one of them is a mobile app or a metrics exporter. The listener list is a copy-on-write list, so a board can subscribe while gates are busy without any locking.
interface AvailabilityListener {
void onChange(SpotSize s, long free);
}
listeners = new CopyOnWriteArrayList
after every park or release:
for (l : listeners) l.onChange(..)
boards, a mobile app, metrics:
all just subscribe Flow: entry
Walk the entry flow. First reject a plate that is already inside. Ask the strategy for candidate spots in order. Try to claim each one; if another gate got it first, move to the next. Once a spot is ours, create the ticket with the time from an injected clock, store it in a map of active tickets, and tell the boards. If no candidate works, throw a clear lot-full error for that vehicle type.
reject if plate already inside
for (Spot s : strategy.candidates(..)) {
if (!s.tryPark(v)) continue;
Ticket t = new Ticket(nextId(), v, s,
clock.get());
active.put(t.id(), t);
publish(s.size);
return t;
}
throw: no free spot for this type Flow: exit
The exit flow. Remove the ticket from the active map first: that single atomic step means a ticket can only ever be used once, even if two exits race. Price the stay, charge the payment method, and if the payment is declined, put the ticket back because the car is still inside. Only after a successful charge do we release the spot, notify the boards and return a receipt.
t = active.remove(ticketId)
if (t == null) throw: used or unknown
fee = pricing.feeCents(t, now)
if (!payment.charge(fee)) {
active.put(ticketId, t) // put back
throw: payment declined
}
t.spot().release()
publish(size); return receipt Concurrency
Now the part that separates good answers from great ones: concurrency. Two gates both see spot one-M-two as free at the same instant. If parking were check-then-set, both would win and two cars would share a spot. Instead each spot holds an atomic reference, and parking is a compare-and-set from empty to this vehicle. Exactly one gate succeeds; the loser simply tries its next candidate. No global lock, so gates never wait on each other.
Go through every shared field and give it a safe home. Spot state is atomic. Active tickets live in a concurrent hash map. A plate is reserved with put-if-absent, so the same car cannot enter twice through two gates. Ticket numbers come from an atomic counter. Listeners sit in a copy-on-write list. And everything else is an immutable record, which is safe to share without any locking at all.
AtomicReference<Vehicle> parked
boolean tryPark(Vehicle v) {
return parked.compareAndSet(null, v);
}
gate 1 and gate 2 both see 1-M2 free
gate 1: null to car A, true
gate 2: expected null, false
so it tries the next candidate - spot state: AtomicReference
- active tickets: ConcurrentHashMap
- plate already inside:
- putIfAbsent on plate map
- ticket ids: AtomicLong
- listeners: CopyOnWriteArrayList
- ticket used once:
- remove() before charging
- records are immutable:
- safe to share freely
Extensibility
Interviewers love to change the requirements halfway. Electric charging spots? Add a feature to the spot and an EV-first strategy. Reservations? A reservation object that holds a spot until a time. Monthly passes? A pricing decorator that returns zero for pass holders and delegates otherwise. A new vehicle type? The switch forces you to decide where it fits. Each change is a new class rather than a risky edit.
- EV spots: new SpotSize or a
- feature flag + EvFirstStrategy
- reservations: a Reservation
- holds a spot until a time
- monthly passes: a Pricing
- decorator that returns 0
- new vehicle type: compiler
- forces a fits() decision
- many lots: a LotRegistry
- keyed by lot id
Testing
The full code is below the player. The demo parks a car, a bike and a truck, moves a fake clock forward two and a half hours and checks the fee, then starts eight threads that race for four medium spots. Exactly four park and four are turned away, every time. Injecting the clock as a supplier is what makes the pricing testable without sleeping, so mention it.
KA01AB1234 -> 1-M2
KA02XY9 -> 1-S1
KA03TR77 -> 1-L4
Receipt: KA01AB1234 stayed 150 min,
paid 6.00
Race: 4 medium free, 4 parked,
4 turned away
clock is a Supplier<Instant>, so the
test moves time without sleeping Follow-ups
Expect follow-ups. Why not one synchronized method? It works, but every gate would queue behind every other gate, and compare-and-set avoids that. What if the process restarts? Tickets move to a database with the spot id as a unique key. Nearest spot to an exit? Keep a heap of free spots per size per exit. And which design principles did you use? Single responsibility for each class, and open-closed through the strategies.
- why not one big synchronized?
- what if the app server dies?
- persist tickets in a DB
- lost ticket: daily maximum
- how do boards stay correct
- after a crash? recount
- nearest spot to the exit:
- a heap per size per gate
- which SOLID principles?
- open-closed, single resp.
Say it like this
Here is the short version to say out loud. The lot has floors, floors have spots, and a spot holds at most one vehicle. Spot choice, pricing and payment are strategies, and display boards are observers. Parking is a compare-and-set on the spot, so two gates never share one. Tickets live in a concurrent map and are removed exactly once. New rules arrive as new classes, not edits.
- "Lot has floors, floors have
- spots, a spot holds one vehicle.
- Spot choice, pricing and
- payment are strategies; boards
- are observers. Parking is a
- compare-and-set on the spot,
- tickets live in a concurrent
- map and are removed once.
- New rules are new classes."