On this page

Mock Interview: Design a Parking Lot

This page is a complete LLD interview, written out as a transcript. The candidate is a mid-level engineer, the interviewer runs a standard 45-minute round, and the prompt is the most commonly asked LLD question there is. Between the lines of dialogue you'll find commentary boxes. Green tips mark moments that earn credit, and yellow warnings mark moments that cost it, or nearly do.

The candidate isn't perfect, deliberately. They make three mistakes that real candidates make all the time, and you'll see how each one is caught and recovered from. Watching a recovery is more useful than watching a flawless run, because recoveries are what real interviews are made of.

The interview follows the 45-minute framework. Timestamps are shown at each step so you can see how the budget plays out. The scoring commentary uses the signals from How LLD Interviews Are Scored. If you want the parking lot as a reference case study rather than a live session, see Design a Parking Lot. The design that comes out of this interview differs from that page in a few places, which is normal, because there's no single correct answer.

An illustrative transcript

This conversation is invented for teaching. It's modelled on how these rounds typically run, not on a recording of a real interview at any company.

00:00 The prompt

Interviewer: Thanks for joining. For this round I'd like you to design a parking lot. We're interested in the object model and the core logic, not the hardware or the UI. You can use the shared editor for diagrams and code. Any language is fine. Take it wherever you think it should go, and I'll jump in with questions.

Candidate: Sounds good. I'll use Java for code, since its interfaces make the structure easy to read, and Mermaid for diagrams. Before I design anything, I'd like to spend about five minutes on requirements, so I'm designing the right parking lot. I'll write down what we agree as I go.

Setting the agenda

The candidate has said the language, the tools and the plan for the next five minutes, all in three sentences. The interviewer now knows the candidate will drive, which is the "communication" signal at mid-level. It also buys the candidate permission to ask questions without seeming to stall.

00:40 Clarifying requirements

Candidate: First, who uses the system? I'm picturing drivers who enter and exit through gates, and maybe an operator who configures the lot. Is that right?

Interviewer: Yes. Drivers at entry and exit gates. An admin sets up the lot. You can treat setup as simple.

Candidate: And the lot itself: several levels, each with spots of different sizes?

Interviewer: Multiple levels, yes. Sizes are up to you.

Candidate: I'll propose three spot sizes, small, medium and large, and three vehicle types: motorbikes, cars and vans. A vehicle can park in its own size or bigger. A motorbike can use any spot, a car can use medium or large, and a van needs large. Does that work?

Interviewer: That works.

Candidate: When a car arrives, which spot does it get? I'd default to the lowest level, smallest spot that fits, so we don't waste large spots on motorbikes. But I can imagine the business wanting other rules, like nearest the exit, or reserving some spots.

Interviewer: Smallest-fit on the lowest level is fine for now. Keep in mind it might change.

Candidate: Noted. That's a hint to make allocation pluggable. Next, pricing. How is a stay charged?

Interviewer: By the hour, with different rates for different vehicle types. You choose the details.

Candidate: Then I'll say: a grace period of 15 minutes is free, after that it's charged per started hour. A motorbike is 1.00 an hour, a car 2.00 and a van 3.50. Fees are calculated at exit. Do we take payment, or just compute the amount?

Interviewer: Just compute it. Payment's out of scope.

Candidate: Two more. Can several entry and exit gates operate at the same time?

Interviewer: Yes, there are four gates.

Candidate: And is this in-memory, or do I need to think about persistence?

Interviewer: In-memory is fine.

Candidate: Let me write that down.

IN SCOPE
- Levels with SMALL / MEDIUM / LARGE spots
- MOTORBIKE fits any, CAR fits MEDIUM+, VAN fits LARGE
- Entry: assign lowest-level, smallest fitting spot, issue a ticket
- Exit: compute fee, free the spot
- Fee: first 15 min free, then per started hour, rate by vehicle type
- 4 gates operating concurrently
- Lot full / vehicle already inside -> clear errors

OUT OF SCOPE
- Payment processing, hardware, UI, persistence

LIKELY TO CHANGE
- Allocation rule (nearest exit, reserved spots)
- Pricing (peak hours, flat day rate)

Candidate: Is that what you had in mind?

Interviewer: Yes, that's a good scope.

What earned credit here

  • Proposing rather than asking. "I'll propose three sizes" moves faster than "what sizes are there?", and it shows judgement.
  • Hearing the hint. "Keep in mind it might change" is the interviewer signalling a future extension. The candidate said aloud that this means making allocation pluggable.
  • Asking about concurrency early. Four gates means shared state. Learning that in minute four, rather than minute 38, shapes the method boundaries.
  • Writing it down. The "likely to change" list will justify both interfaces later.

A small miss

The candidate didn't ask what happens if a ticket is lost, or whether a vehicle can leave without a ticket. Neither matters much for the design, but an edge case like this is something an interviewer may raise later. Asking one "what goes wrong" question during clarification is a cheap way to show edge-case thinking.

05:00 Use cases

Candidate: Here are the flows I'll design for:

UC1  Driver enters        -> spot assigned, ticket issued
UC2  Driver exits         -> fee computed, spot freed
UC3  Lot has no fitting spot -> entry rejected with a reason
UC4  Same plate enters twice -> rejected
UC5  Two gates admit cars at the same moment -> never the same spot
UC6  Admin configures levels and spots (setup only)

Candidate: UC1 and UC2 are what I'll code. UC3 to UC5 are the edge cases that shape the design. UC6 I'll treat as constructor setup.

Interviewer: Fine. What about a vehicle trying to exit with a ticket that's already been used?

Candidate: Good one. That's UC7: exit with an unknown or already-used ticket is rejected. It also means a ticket can only be closed once.

Turning the interviewer's question into a use case

The interviewer has just raised the edge case the candidate missed in clarification. The candidate didn't defend or apologise. They added it to the list and noted the invariant it implies ("a ticket can only be closed once"). That's taking a hint well.

08:00 Entities and relationships

Candidate: Pulling out the nouns: parking lot, level, spot, vehicle, ticket, gate, fee. Here's what I'll do with them.

Candidate: ParkingLot is the coordinator. It holds levels and active tickets, and it's what the gates call. Level holds spots. Spot has an id, a size, and who's in it. For Vehicle, I'd make an abstract Vehicle class with Motorbike, Car and Van subclasses, each overriding a getSize() method.

Interviewer: What would the subclasses do differently from each other?

Candidate: They'd each return a different size... and probably a different rate.

Interviewer: Anything else?

Candidate: Hmm, no. That's all they'd do. So they differ only in data, not behaviour. Then a hierarchy isn't pulling its weight. I'll make VehicleType an enum that carries its minimum spot size, and Vehicle a small value with a plate and a type. If later a vehicle type needs genuinely different behaviour, I can revisit.

Interviewer: OK.

Mistake 1: inheritance by default

Vehicle with three empty-ish subclasses is the most common parking-lot modelling choice, and interviewers often probe it exactly like this. The subclasses would differ only in two constants. That's inheritance abuse: a type hierarchy where a field would do.

The recovery was good. The candidate answered the probing question honestly, saw the implication and changed course without fuss. Defending the hierarchy ("it's more extensible") would have cost far more than the original choice did.

Candidate: Continuing. Ticket records the vehicle, the spot and the entry time, and it gets an id. It's created at entry and closed at exit. Gates aren't classes for now. They're callers of ParkingLot, and nothing in scope gives them behaviour. Fee is computed by a pricing policy, which is on the "likely to change" list, so it'll be an interface. The same goes for spot selection.

Candidate: Relationships: a lot has many levels, a level has many spots, both by composition, since a spot doesn't exist outside its level. A ticket refers to one spot and one vehicle. At any moment, a spot has at most one active ticket, and a plate has at most one active ticket. Those are the two invariants I need to protect.

Interviewer: Where would you enforce them?

Candidate: The spot enforces "one occupant": occupy throws if it's already taken. The lot enforces "one active ticket per plate", because only the lot can see all the tickets. And both checks need to be atomic with the update, because of the four gates. I'll come back to that.

Naming invariants and their owners

"Two invariants, and here's who enforces each one" is a strong modelling statement. It tells the interviewer that the candidate sees the design as a set of guarantees, and it pre-commits the concurrency discussion to protecting something specific. See From Nouns to Classes for the technique.

13:00 Class diagram

Candidate: Let me draw this.

classDiagram
    class ParkingLot {
        -levels: list of Level
        -activeByPlate: map of plate to Ticket
        -activeById: map of id to Ticket
        +enter(vehicle) Ticket
        +exit(ticketId) Receipt
    }
    class Level {
        -number: int
        -spots: list of Spot
    }
    class Spot {
        -id: String
        -size: SpotSize
        -occupant: String
        +fits(type) boolean
        +occupy(plate)
        +vacate()
    }
    class VehicleType {
        <<enumeration>>
        MOTORBIKE
        CAR
        VAN
        +minSpot() SpotSize
    }
    class Vehicle {
        +plate: String
        +type: VehicleType
    }
    class Ticket {
        +id: String
        +vehicle: Vehicle
        +spot: Spot
        +entry: Instant
    }
    class SpotSelector {
        <<interface>>
        +choose(levels, type) Spot
    }
    class PricingPolicy {
        <<interface>>
        +feeCents(type, stay) long
    }
    ParkingLot *-- Level
    Level *-- Spot
    ParkingLot --> SpotSelector
    ParkingLot --> PricingPolicy
    ParkingLot o-- Ticket
    Ticket --> Spot
    Ticket --> Vehicle
    Vehicle --> VehicleType

Candidate: A few notes as I draw. Spot guards its own occupancy, so nobody else flips the flag. ParkingLot keeps two maps of active tickets: by plate, to reject duplicates in O(1), and by ticket id, for exit. Both selector and pricing are interfaces because they're on the change list. Level is deliberately thin. If we needed per-level counts or displays, they'd go there.

Interviewer: Why two maps rather than one?

Candidate: Exit comes in with a ticket id, and entry checks by plate. One map would need a linear scan for one of them. The cost is keeping the two in sync, which is easy because only enter and exit touch them, and both will be under the same lock.

Interviewer: Does this look complete to you?

Candidate: There's a Receipt returned from exit, with the ticket, the exit time and the fee, which I haven't drawn. Otherwise yes. Before I write signatures, is there a part you'd like me to go deeper on?

Interviewer: No, carry on. I'm happy with the shape.

The check-in

Asking "is there a part you'd like me to go deeper on?" before coding is cheap insurance. Sometimes the interviewer wants to see pricing in depth, or allocation, and this is the moment to find out, before 11 minutes of code go in a different direction.

20:00 Interfaces

Candidate: Signatures, with the failure behaviour:

interface SpotSelector {
    /** The spot to use, or empty if nothing free fits. Must not modify the spot. */
    Optional<Spot> choose(List<Level> levels, VehicleType type);
}

interface PricingPolicy {
    /** Fee in cents for a stay of this length. Never negative. */
    long feeCents(VehicleType type, Duration stay);
}

// ParkingLot (concrete, constructed with a selector, a pricing policy and a Clock)
//   Ticket  enter(Vehicle vehicle)   throws ParkingException: lot full, or already inside
//   Receipt exit(String ticketId)    throws ParkingException: unknown or already-closed ticket

Candidate: The lot takes a Clock in its constructor rather than calling Instant.now(), so tests can move time forward and check fees without waiting. The selector returns an Optional and doesn't occupy the spot. Choosing and occupying are separate, so the lot can do both under one lock.

Interviewer: Why separate them? The selector could just occupy the spot it finds.

Candidate: Then the selector would be mutating state, and every new selector would have to get the locking right. Keeping selectors as pure "pick one" functions means the locking lives in one place, the lot.

Explaining a seam in terms of risk

That last answer is a senior-level argument. It's not "separation of concerns" as a slogan. It's "if this mutates, every future implementation has to get concurrency right". Tying an interface boundary to where risk lives is exactly the abstraction signal the rubric describes.

24:00 Core logic

Candidate: I'll write enter and exit properly, since they carry the rules, plus the selector and the pricing. Setup and getters I'll keep short.

The candidate types for a few minutes, narrating as they go.

Candidate: In enter, I check that the plate isn't already inside before choosing a spot, so a duplicate entry has no side effects. Then the selector picks a spot, I occupy it, create the ticket and record it in both maps.

Ticket enter(Vehicle vehicle) {
    if (activeByPlate.containsKey(vehicle.plate()))
        throw new ParkingException(vehicle.plate() + " is already inside");
    Spot spot = selector.choose(levels, vehicle.type())
        .orElseThrow(() -> new ParkingException("no free spot for a " + vehicle.type()));
    spot.occupy(vehicle.plate());
    Ticket ticket = new Ticket("T" + nextTicket++, vehicle, spot, clock.instant());
    activeByPlate.put(vehicle.plate(), ticket);
    activeById.put(ticket.id(), ticket);
    return ticket;
}

Candidate: For pricing, the stay is minus the grace period, rounded up to whole hours, times the hourly rate... so double hours = Math.ceil(minutes / 60.0) and double fee = hours * rate, where the rate is 2.0 for a car...

The candidate pauses.

Candidate: Actually, let me not use double for money. I'll keep rates in cents as long, and do the rounding in integer arithmetic: (billableMinutes + 59) / 60. Then the fee is exact.

public long feeCents(VehicleType type, Duration stay) {
    long billable = stay.toMinutes() - grace.toMinutes();
    if (billable <= 0) return 0;
    long hours = (billable + 59) / 60;          // per started hour
    return hours * centsPerHour.get(type);
}

Mistake 2: floating point for money, caught in time

double fee was on the screen for about ten seconds. Self-correcting before the interviewer comments turns a red flag into a mild positive, because it shows the candidate knows why it's wrong. If the interviewer had had to point it out, it would have gone in the notes as a gap. See primitive obsession for the full argument.

Interviewer: What does a car pay for exactly 15 minutes? And for 16?

Candidate: Fifteen minutes is within the grace period, so zero. At 16 minutes, one billable minute rounds up to one hour, so 2.00. And 1 hour 15 minutes is 60 billable minutes, which is exactly one hour, so also 2.00. I'll put all three in the demo as checks.

Boundaries answered with numbers

The interviewer asked a boundary question, and the candidate answered with concrete values and then turned them into tests. That's the "missing edge cases" trap avoided in real time.

Candidate: Now exit. Look up the ticket by id, and reject it if it's unknown, which also covers already-used tickets, since closed tickets are removed. Compute the fee from entry to now, free the spot and remove the ticket from both maps.

Receipt exit(String ticketId) {
    Ticket ticket = activeById.remove(ticketId);
    if (ticket == null) throw new ParkingException("unknown or already used ticket " + ticketId);
    activeByPlate.remove(ticket.vehicle().plate());
    Instant now = clock.instant();
    long fee = pricing.feeCents(ticket.vehicle().type(), Duration.between(ticket.entry(), now));
    ticket.spot().vacate();
    return new Receipt(ticket, now, fee);
}

Candidate: And the selector, lowest level first, then smallest fitting size:

public Optional<Spot> choose(List<Level> levels, VehicleType type) {
    for (Level level : levels) {
        Optional<Spot> best = level.spots().stream()
            .filter(s -> s.isFree() && s.fits(type))
            .min(Comparator.comparing(Spot::size));
        if (best.isPresent()) return best;
    }
    return Optional.empty();
}

Interviewer: That's a linear scan over every spot. Is that a problem?

Candidate: For a lot with a few thousand spots, a scan per entry takes microseconds, so I'd keep it for now. If it mattered, each level would keep a free set per size, and the selector would check those in size order. That's O(levels × sizes) per entry. The interface doesn't change, so it's a contained optimisation.

Performance answered in proportion

The candidate didn't over-engineer the selector up front, and didn't dismiss the question either. They gave a size estimate, said when it would matter, and described the upgrade path, which fits behind the existing interface. That's the right weight for a performance question in an LLD round.

35:00 Patterns

Interviewer: Can you talk me through the design patterns you've used?

Candidate: Two that matter. Strategy, twice: SpotSelector for allocation and PricingPolicy for fees. Both were on the "likely to change" list, so each new rule, like nearest-to-exit or peak pricing, is a new class, and ParkingLot doesn't change. Then dependency injection: the lot gets its selector, pricing and clock through the constructor, which is what makes fees testable.

Candidate: You could call ParkingLot a facade, since it's the single entry point the gates use. I considered a State pattern for spots, but a spot only has free and occupied, so a guarded field is simpler. And I deliberately didn't add a factory for vehicles, because there's nothing to construct beyond a plate and a type.

Interviewer: Would you use a singleton for the parking lot? There's only one.

Candidate: No. There's one lot because main creates one. If the class enforced it, tests couldn't create a fresh lot each time, and we couldn't model two lots later. "Only one instance" is a wiring decision.

Patterns tied to requirements, with rejections

Each pattern is linked to a line on the requirements list. The candidate named two patterns they chose not to use, with reasons, and handled the singleton question the way experienced engineers do. Compare this with over-patterning.

38:00 Concurrency

Interviewer: You mentioned four gates. Walk me through what happens if two cars enter at the same time.

Candidate: Right. The shared state is the spots and the two ticket maps. I'd make the maps ConcurrentHashMaps, so concurrent puts are safe.

Interviewer: Would that be enough?

Candidate: Let me trace it. Gate A and gate B both call enter. Both call the selector, and both see spot L1-M3 as free, because neither has occupied it yet. Both call occupy... and one of them would throw, since occupy checks. But that's luck. If occupy didn't check, we'd double-assign. And the duplicate-plate check has the same problem: two gates could both see a plate as not inside. So no, concurrent maps make each individual operation safe, but the problem is the sequence: check, choose, occupy, record. That whole sequence has to be atomic.

Candidate: So I'll make enter and exit synchronized on the lot, meaning one lock for the whole sequence. Then the maps don't need to be concurrent at all.

Interviewer: Doesn't that serialise all four gates?

Candidate: It does, and I think that's fine here. An entry takes microseconds inside the lock, and cars arrive every few seconds per gate at most. So contention is negligible. If we needed more, I'd lock per level: the selector tries levels in order and locks only the level it's choosing in. The plate-uniqueness check would then need its own small lock, or an atomic putIfAbsent on the plate map done first, as a reservation, and rolled back if no spot is found. That's more complex, so I'd only do it with a measured need.

Mistake 3: reaching for a thread-safe collection

"Use a ConcurrentHashMap" is the most common incomplete concurrency answer. Thread-safe collections make single operations atomic, but here the invariant spans a sequence of operations across several objects. The interviewer's "would that be enough?" was a hint, and the candidate took it well. They traced the interleaving step by step, found the real problem themselves, and fixed it.

A stronger answer would have started from the invariant rather than the data structure. See ignoring concurrency.

Granularity with a cost model

The follow-up answer is strong. It names the cost of the coarse lock, estimates why it doesn't matter, and describes the finer-grained alternative, including the new problem that alternative creates (the plate check across levels). Interviewers at senior level look for exactly that. For a deeper dive, see race conditions.

sequenceDiagram
    participant A as Gate A
    participant L as ParkingLot
    participant S as SpotSelector
    participant P as Spot L1-M3
    participant B as Gate B
    A->>L: enter(car KA-01)
    Note over L: lock acquired by Gate A
    B->>L: enter(car KA-02)
    Note over B,L: Gate B waits for the lock
    L->>S: choose(levels, CAR)
    S-->>L: L1-M3
    L->>P: occupy(KA-01)
    L-->>A: Ticket T1
    Note over L: lock released, Gate B proceeds
    L->>S: choose(levels, CAR)
    S-->>L: L1-M4, since L1-M3 is now taken
    L-->>B: Ticket T2

41:00 Extensions

Interviewer: Let's add something. The owner wants some spots to have EV chargers. Electric vehicles should prefer a charger spot if one is free, and non-electric vehicles should avoid charger spots unless nothing else fits. What changes?

Candidate: Three things. First, a spot gains a feature: boolean hasCharger, or a feature set if we expect more features. Second, a vehicle gains boolean electric. Third, a new selector. It runs the same smallest-fit search, but ranks spots by "charger matches the vehicle's need" first. EV-to-charger is preferred, and non-EV-to-non-charger is preferred. Then size, then level.

final class EvAwareSelector implements SpotSelector {
    public Optional<Spot> choose(List<Level> levels, Vehicle vehicle) {
        return levels.stream()
            .flatMap(l -> l.spots().stream())
            .filter(s -> s.isFree() && s.fits(vehicle.type()))
            .min(Comparator
                .comparing((Spot s) -> s.hasCharger() != vehicle.electric())  // mismatch sorts last
                .thenComparing(Spot::size)
                .thenComparing(Spot::level));
    }
}

Candidate: I'm being honest that this touches the interface. The selector now needs the whole Vehicle, not just the type. So choose changes signature, and the existing selector changes one line to read vehicle.type(). ParkingLot passes the vehicle instead of its type. Pricing, tickets and exit don't change.

Interviewer: Could you have avoided changing the interface?

Candidate: If I'd passed the whole Vehicle from the start, yes. In hindsight that's the better signature: give the strategy the domain object, not a field from it, since future rules will want more of it. I'd make that change now.

Honest about the cost of a change

The candidate didn't pretend the extension was free. They named the one signature change, said what else stays the same, and drew the right lesson ("pass the domain object, not a field"). Interviewers trust candidates who can say "in hindsight". The final code below uses the improved signature.

Interviewer: One more. Peak pricing: 1.5 times the rate for stays that start between 8am and 10am.

Candidate: That's a new PricingPolicy that wraps another one. It's a decorator. PeakPricing(base, multiplierPercent, peakStart, peakEnd) calls the base policy and scales the result if the entry time falls in the window. To decide that, the policy needs the entry time, so feeCents should take the ticket, or the entry and exit instants, instead of just a duration. Same lesson as before: give the policy the domain object. I'd change feeCents(type, stay) to feeCents(ticket, exitTime).

Interviewer: Good. Let's wrap up.

44:00 Wrap-up

Candidate: To summarise. ParkingLot coordinates and holds the active tickets. Spot guards its own occupancy. Allocation and pricing are strategies, because both were flagged as likely to change. Money is in integer cents, and time comes from an injected clock, so the fee boundaries are testable. One lock makes entry and exit atomic across gates. That's cheap at this scale, and per-level locking is the upgrade path. From the extensions, I'd pass the whole vehicle to selectors and the whole ticket to pricing.

Candidate: Known gaps: no lost-ticket flow, no reservations, and no tests written as such, though the demo checks the boundaries. If I had ten more minutes, I'd write tests for the grace-period boundaries and the concurrent-entry case.

Interviewer: Thanks, that's time.

A wrap-up that hands over the notes

In 40 seconds the candidate restated every design decision, the reason for each, the concurrency choice and its cost, the lessons from the extensions, and the known gaps. An interviewer writing feedback afterwards can almost copy it into the form.

How this interview might be scored

Here's an illustrative scorecard using the rubric signals, assessed at mid-level.

SignalEvidenceAssessment
ModellingRecovered from the vehicle hierarchy to an enum. Invariants named with owners.Meets, after a hint
AbstractionTwo interfaces, both tied to stated change. Selector kept pure for locking reasons.Strong
PrinciplesSRP in Spot and the lot. OCP via strategies. DIP via constructor injection.Meets
ExtensibilityEV handled with a located change, honest about the signature change. Peak pricing as a decorator.Strong
Code qualityClean enter and exit, validate-then-mutate, double self-corrected.Meets
TestabilityInjected clock, concrete boundary values. No tests written.Meets
ConcurrencyFirst answer incomplete. Traced the race after a hint, then gave a good granularity discussion.Meets, after a hint
CommunicationDrove the session, checked in at milestones, took every hint well, clean wrap-up.Strong

Overall: a solid hire at mid-level. Two signals needed a hint (modelling and concurrency), which keeps it short of a senior-level hire. A senior candidate would be expected to avoid the hierarchy and start the concurrency discussion from the invariant without prompting.

The final design

Here's the design after folding in the lessons from the extensions. Selectors receive the whole Vehicle, and pricing receives the Ticket and the exit time. EV support and peak pricing are included, because they're cheap with these signatures.

classDiagram
    class ParkingLot {
        -levels: list of Level
        -selector: SpotSelector
        -pricing: PricingPolicy
        -clock: Clock
        -activeByPlate: map of plate to Ticket
        -activeById: map of id to Ticket
        +enter(vehicle) Ticket
        +exit(ticketId) Receipt
        +freeSpots() int
    }
    class Level {
        +number: int
        +spots: list of Spot
    }
    class Spot {
        +id: String
        +level: int
        +size: SpotSize
        +hasCharger: boolean
        -occupant: String
        +isFree() boolean
        +fits(type) boolean
        +occupy(plate)
        +vacate()
    }
    class SpotSize {
        <<enumeration>>
        SMALL
        MEDIUM
        LARGE
    }
    class VehicleType {
        <<enumeration>>
        MOTORBIKE
        CAR
        VAN
        +minSpot: SpotSize
    }
    class Vehicle {
        +plate: String
        +type: VehicleType
        +electric: boolean
    }
    class Ticket {
        +id: String
        +vehicle: Vehicle
        +spot: Spot
        +entry: Instant
    }
    class Receipt {
        +ticket: Ticket
        +exit: Instant
        +feeCents: long
    }
    class SpotSelector {
        <<interface>>
        +choose(levels, vehicle) Spot
    }
    class SmallestFitSelector
    class EvAwareSelector
    class PricingPolicy {
        <<interface>>
        +feeCents(ticket, exit) long
    }
    class HourlyPricing {
        -centsPerHour: rate per VehicleType
        -grace: Duration
    }
    class PeakPricing {
        -base: PricingPolicy
        -multiplierPercent: int
        -peakStartHour: int
        -peakEndHour: int
    }
    ParkingLot *-- Level
    Level *-- Spot
    Spot --> SpotSize
    VehicleType --> SpotSize
    Vehicle --> VehicleType
    ParkingLot o-- Ticket
    Ticket --> Vehicle
    Ticket --> Spot
    Receipt --> Ticket
    ParkingLot --> SpotSelector
    ParkingLot --> PricingPolicy
    SpotSelector <|.. SmallestFitSelector
    SpotSelector <|.. EvAwareSelector
    PricingPolicy <|.. HourlyPricing
    PricingPolicy <|.. PeakPricing
    PeakPricing --> PricingPolicy : wraps
sequenceDiagram
    actor G as Exit gate
    participant L as ParkingLot
    participant P as PricingPolicy
    participant S as Spot
    G->>L: exit(T7)
    Note over L: lock held for the whole exit
    L->>L: remove T7 from activeById, or fail if absent
    L->>L: remove plate from activeByPlate
    L->>P: feeCents(ticket, now)
    P-->>L: 400
    L->>S: vacate()
    L-->>G: Receipt with fee 4.00

The final code

Complete and runnable in all three languages. Each main builds a two-level lot and checks the behaviour discussed in the interview: smallest fit, lot full, duplicate entry, the grace-period boundaries, a reused ticket, EV preference, peak pricing, and twenty concurrent entries competing for ten spots.

import java.time.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

enum SpotSize { SMALL, MEDIUM, LARGE }

enum VehicleType {
    MOTORBIKE(SpotSize.SMALL), CAR(SpotSize.MEDIUM), VAN(SpotSize.LARGE);
    final SpotSize minSpot;
    VehicleType(SpotSize minSpot) { this.minSpot = minSpot; }
}

class ParkingException extends RuntimeException {
    ParkingException(String message) { super(message); }
}

record Vehicle(String plate, VehicleType type, boolean electric) {
    Vehicle(String plate, VehicleType type) { this(plate, type, false); }
}

final class Spot {
    private final String id;
    private final int level;
    private final SpotSize size;
    private final boolean hasCharger;
    private String occupant; // plate, or null when free

    Spot(String id, int level, SpotSize size, boolean hasCharger) {
        this.id = id; this.level = level; this.size = size; this.hasCharger = hasCharger;
    }
    String id() { return id; }
    int level() { return level; }
    SpotSize size() { return size; }
    boolean hasCharger() { return hasCharger; }
    boolean isFree() { return occupant == null; }
    boolean fits(VehicleType type) { return size.compareTo(type.minSpot) >= 0; }

    void occupy(String plate) {
        if (!isFree()) throw new ParkingException("spot " + id + " is already occupied");
        occupant = plate;
    }
    void vacate() { occupant = null; }
}

record Level(int number, List<Spot> spots) {}

record Ticket(String id, Vehicle vehicle, Spot spot, Instant entry) {}

record Receipt(Ticket ticket, Instant exit, long feeCents) {}

interface SpotSelector {
    /** Picks a free spot that fits, without modifying it. */
    Optional<Spot> choose(List<Level> levels, Vehicle vehicle);
}

final class SmallestFitSelector implements SpotSelector {
    public Optional<Spot> choose(List<Level> levels, Vehicle vehicle) {
        for (Level level : levels) {
            Optional<Spot> best = level.spots().stream()
                .filter(s -> s.isFree() && s.fits(vehicle.type()))
                .min(Comparator.comparing(Spot::size));
            if (best.isPresent()) return best;
        }
        return Optional.empty();
    }
}

final class EvAwareSelector implements SpotSelector {
    public Optional<Spot> choose(List<Level> levels, Vehicle vehicle) {
        return levels.stream()
            .flatMap(l -> l.spots().stream())
            .filter(s -> s.isFree() && s.fits(vehicle.type()))
            .min(Comparator
                .comparing((Spot s) -> s.hasCharger() != vehicle.electric()) // a mismatch sorts last
                .thenComparing(Spot::size)
                .thenComparing(Spot::level));
    }
}

interface PricingPolicy {
    /** Fee in cents. Never negative. */
    long feeCents(Ticket ticket, Instant exit);
}

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;
    }

    public long feeCents(Ticket ticket, Instant exit) {
        long billable = Duration.between(ticket.entry(), exit).minus(grace).toMinutes();
        if (billable <= 0) return 0;
        long hours = (billable + 59) / 60; // per started hour
        return hours * centsPerHour.get(ticket.vehicle().type());
    }
}

final class PeakPricing implements PricingPolicy {
    private final PricingPolicy base;
    private final int multiplierPercent, peakStartHour, peakEndHour;
    private final ZoneId zone;

    PeakPricing(PricingPolicy base, int multiplierPercent, int peakStartHour, int peakEndHour, ZoneId zone) {
        this.base = base; this.multiplierPercent = multiplierPercent;
        this.peakStartHour = peakStartHour; this.peakEndHour = peakEndHour; this.zone = zone;
    }

    public long feeCents(Ticket ticket, Instant exit) {
        long fee = base.feeCents(ticket, exit);
        int hour = ticket.entry().atZone(zone).getHour();
        boolean peak = hour >= peakStartHour && hour < peakEndHour;
        return peak ? fee * multiplierPercent / 100 : fee;
    }
}

final class ParkingLot {
    private final List<Level> levels;
    private final SpotSelector selector;
    private final PricingPolicy pricing;
    private final Clock clock;
    private final Map<String, Ticket> activeByPlate = new HashMap<>();
    private final Map<String, Ticket> activeById = new HashMap<>();
    private long nextTicket = 1;

    ParkingLot(List<Level> levels, SpotSelector selector, PricingPolicy pricing, Clock clock) {
        this.levels = List.copyOf(levels); this.selector = selector; this.pricing = pricing; this.clock = clock;
    }

    synchronized Ticket enter(Vehicle vehicle) {
        if (activeByPlate.containsKey(vehicle.plate()))
            throw new ParkingException(vehicle.plate() + " is already inside");
        Spot spot = selector.choose(levels, vehicle)
            .orElseThrow(() -> new ParkingException("no free spot for a " + vehicle.type()));
        spot.occupy(vehicle.plate());
        Ticket ticket = new Ticket("T" + nextTicket++, vehicle, spot, clock.instant());
        activeByPlate.put(vehicle.plate(), ticket);
        activeById.put(ticket.id(), ticket);
        return ticket;
    }

    synchronized Receipt exit(String ticketId) {
        Ticket ticket = activeById.remove(ticketId);
        if (ticket == null) throw new ParkingException("unknown or already used ticket " + ticketId);
        activeByPlate.remove(ticket.vehicle().plate());
        Instant now = clock.instant();
        long fee = pricing.feeCents(ticket, now);
        ticket.spot().vacate();
        return new Receipt(ticket, now, fee);
    }

    synchronized int freeSpots() {
        return (int) levels.stream().flatMap(l -> l.spots().stream()).filter(Spot::isFree).count();
    }
}

public class ParkingDemo {
    static final class TestClock extends Clock {
        Instant now = Instant.parse("2026-03-02T07:00:00Z");
        public ZoneId getZone() { return ZoneOffset.UTC; }
        public Clock withZone(ZoneId zone) { return this; }
        public Instant instant() { return now; }
        void advance(Duration d) { now = now.plus(d); }
    }

    static void check(boolean ok, String what) {
        if (!ok) throw new AssertionError("FAILED: " + what);
        System.out.println("ok  " + what);
    }

    static void expectError(Runnable action, String fragment, String what) {
        try { action.run(); } catch (ParkingException e) { check(e.getMessage().contains(fragment), what); return; }
        check(false, what);
    }

    static List<Level> smallLot() {
        return List.of(
            new Level(1, List.of(new Spot("L1-S1", 1, SpotSize.SMALL, false),
                                 new Spot("L1-M1", 1, SpotSize.MEDIUM, false))),
            new Level(2, List.of(new Spot("L2-M1", 2, SpotSize.MEDIUM, true),
                                 new Spot("L2-L1", 2, SpotSize.LARGE, false))));
    }

    static final Map<VehicleType, Long> RATES =
        Map.of(VehicleType.MOTORBIKE, 100L, VehicleType.CAR, 200L, VehicleType.VAN, 350L);

    public static void main(String[] args) throws Exception {
        TestClock clock = new TestClock();
        PricingPolicy hourly = new HourlyPricing(RATES, Duration.ofMinutes(15));
        ParkingLot lot = new ParkingLot(smallLot(), new SmallestFitSelector(), hourly, clock);

        Ticket bike = lot.enter(new Vehicle("BIKE-1", VehicleType.MOTORBIKE));
        check(bike.spot().id().equals("L1-S1"), "motorbike takes the smallest spot on level 1");
        Ticket car = lot.enter(new Vehicle("CAR-1", VehicleType.CAR));
        check(car.spot().id().equals("L1-M1"), "car takes the medium spot on level 1");
        expectError(() -> lot.enter(new Vehicle("CAR-1", VehicleType.CAR)), "already inside", "duplicate plate rejected");
        Ticket van = lot.enter(new Vehicle("VAN-1", VehicleType.VAN));
        check(van.spot().id().equals("L2-L1"), "van goes to the large spot on level 2");
        lot.enter(new Vehicle("CAR-2", VehicleType.CAR));
        expectError(() -> lot.enter(new Vehicle("CAR-3", VehicleType.CAR)), "no free spot", "full lot rejects entry");

        clock.advance(Duration.ofMinutes(15));
        check(lot.exit(bike.id()).feeCents() == 0, "15 minutes is inside the grace period");
        clock.advance(Duration.ofMinutes(1));
        check(lot.exit(car.id()).feeCents() == 200, "16 minutes costs one hour for a car");
        clock.advance(Duration.ofMinutes(59));
        check(lot.exit(van.id()).feeCents() == 350, "1h15m is exactly one billable hour");
        expectError(() -> lot.exit(car.id()), "already used", "a ticket cannot be used twice");

        // EV preference
        TestClock evClock = new TestClock();
        ParkingLot evLot = new ParkingLot(smallLot(), new EvAwareSelector(), hourly, evClock);
        check(evLot.enter(new Vehicle("EV-1", VehicleType.CAR, true)).spot().hasCharger(), "EV prefers a charger spot");
        check(!evLot.enter(new Vehicle("CAR-9", VehicleType.CAR)).spot().hasCharger(), "non-EV avoids the charger spot");

        // Peak pricing: entry at 08:30 UTC, stay 2h, car rate 200 x 2 hours x 150%
        TestClock peakClock = new TestClock();
        peakClock.now = Instant.parse("2026-03-02T08:30:00Z");
        PricingPolicy peak = new PeakPricing(hourly, 150, 8, 10, ZoneOffset.UTC);
        ParkingLot peakLot = new ParkingLot(smallLot(), new SmallestFitSelector(), peak, peakClock);
        Ticket t = peakLot.enter(new Vehicle("CAR-P", VehicleType.CAR));
        peakClock.advance(Duration.ofMinutes(120));
        check(peakLot.exit(t.id()).feeCents() == 600, "peak entry pays 150 percent");

        // Concurrency: 20 cars race for 10 medium spots, each spot is used exactly once
        List<Spot> spots = new ArrayList<>();
        for (int i = 0; i < 10; i++) spots.add(new Spot("M" + i, 1, SpotSize.MEDIUM, false));
        ParkingLot busy = new ParkingLot(List.of(new Level(1, spots)), new SmallestFitSelector(), hourly, clock);
        ExecutorService gates = Executors.newFixedThreadPool(4);
        Set<String> assigned = ConcurrentHashMap.newKeySet();
        AtomicInteger rejected = new AtomicInteger();
        List<Callable<Void>> arrivals = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            String plate = "C" + i;
            arrivals.add(() -> {
                try { assigned.add(busy.enter(new Vehicle(plate, VehicleType.CAR)).spot().id()); }
                catch (ParkingException e) { rejected.incrementAndGet(); }
                return null;
            });
        }
        gates.invokeAll(arrivals);
        gates.shutdown();
        check(assigned.size() == 10 && rejected.get() == 10 && busy.freeSpots() == 0,
              "concurrent entries: 10 distinct spots assigned, 10 rejected");
    }
}
from __future__ import annotations

import threading
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from enum import Enum
from typing import Callable, Protocol


class SpotSize(Enum):
    SMALL = 1
    MEDIUM = 2
    LARGE = 3


class VehicleType(Enum):
    MOTORBIKE = SpotSize.SMALL
    CAR = SpotSize.MEDIUM
    VAN = SpotSize.LARGE

    @property
    def min_spot(self) -> SpotSize:
        return self.value


class ParkingError(Exception):
    pass


@dataclass(frozen=True)
class Vehicle:
    plate: str
    type: VehicleType
    electric: bool = False


class Spot:
    def __init__(self, spot_id: str, level: int, size: SpotSize, has_charger: bool = False) -> None:
        self.id, self.level, self.size, self.has_charger = spot_id, level, size, has_charger
        self._occupant: str | None = None

    def is_free(self) -> bool:
        return self._occupant is None

    def fits(self, vehicle_type: VehicleType) -> bool:
        return self.size.value >= vehicle_type.min_spot.value

    def occupy(self, plate: str) -> None:
        if not self.is_free():
            raise ParkingError(f"spot {self.id} is already occupied")
        self._occupant = plate

    def vacate(self) -> None:
        self._occupant = None


@dataclass(frozen=True)
class Level:
    number: int
    spots: list[Spot]


@dataclass(frozen=True)
class Ticket:
    id: str
    vehicle: Vehicle
    spot: Spot
    entry: datetime


@dataclass(frozen=True)
class Receipt:
    ticket: Ticket
    exit: datetime
    fee_cents: int


class SpotSelector(Protocol):
    def choose(self, levels: list[Level], vehicle: Vehicle) -> Spot | None: ...


class SmallestFitSelector:
    def choose(self, levels: list[Level], vehicle: Vehicle) -> Spot | None:
        for level in levels:
            fitting = [s for s in level.spots if s.is_free() and s.fits(vehicle.type)]
            if fitting:
                return min(fitting, key=lambda s: s.size.value)
        return None


class EvAwareSelector:
    def choose(self, levels: list[Level], vehicle: Vehicle) -> Spot | None:
        fitting = [s for lvl in levels for s in lvl.spots if s.is_free() and s.fits(vehicle.type)]
        return min(fitting, key=lambda s: (s.has_charger != vehicle.electric, s.size.value, s.level),
                   default=None)


class PricingPolicy(Protocol):
    def fee_cents(self, ticket: Ticket, exit_time: datetime) -> int: ...


class HourlyPricing:
    def __init__(self, cents_per_hour: dict[VehicleType, int], grace: timedelta) -> None:
        self._rates = dict(cents_per_hour)
        self._grace = grace

    def fee_cents(self, ticket: Ticket, exit_time: datetime) -> int:
        billable = int((exit_time - ticket.entry - self._grace).total_seconds() // 60)
        if billable <= 0:
            return 0
        hours = (billable + 59) // 60  # per started hour
        return hours * self._rates[ticket.vehicle.type]


class PeakPricing:
    def __init__(self, base: PricingPolicy, multiplier_percent: int, start_hour: int, end_hour: int) -> None:
        self._base, self._mult, self._start, self._end = base, multiplier_percent, start_hour, end_hour

    def fee_cents(self, ticket: Ticket, exit_time: datetime) -> int:
        fee = self._base.fee_cents(ticket, exit_time)
        return fee * self._mult // 100 if self._start <= ticket.entry.hour < self._end else fee


class ParkingLot:
    def __init__(self, levels: list[Level], selector: SpotSelector, pricing: PricingPolicy,
                 now: Callable[[], datetime]) -> None:
        self._levels = list(levels)
        self._selector, self._pricing, self._now = selector, pricing, now
        self._by_plate: dict[str, Ticket] = {}
        self._by_id: dict[str, Ticket] = {}
        self._next = 1
        self._lock = threading.Lock()

    def enter(self, vehicle: Vehicle) -> Ticket:
        with self._lock:
            if vehicle.plate in self._by_plate:
                raise ParkingError(f"{vehicle.plate} is already inside")
            spot = self._selector.choose(self._levels, vehicle)
            if spot is None:
                raise ParkingError(f"no free spot for a {vehicle.type.name}")
            spot.occupy(vehicle.plate)
            ticket = Ticket(f"T{self._next}", vehicle, spot, self._now())
            self._next += 1
            self._by_plate[vehicle.plate] = ticket
            self._by_id[ticket.id] = ticket
            return ticket

    def exit(self, ticket_id: str) -> Receipt:
        with self._lock:
            ticket = self._by_id.pop(ticket_id, None)
            if ticket is None:
                raise ParkingError(f"unknown or already used ticket {ticket_id}")
            del self._by_plate[ticket.vehicle.plate]
            now = self._now()
            fee = self._pricing.fee_cents(ticket, now)
            ticket.spot.vacate()
            return Receipt(ticket, now, fee)

    def free_spots(self) -> int:
        with self._lock:
            return sum(s.is_free() for lvl in self._levels for s in lvl.spots)


RATES = {VehicleType.MOTORBIKE: 100, VehicleType.CAR: 200, VehicleType.VAN: 350}


def small_lot() -> list[Level]:
    return [Level(1, [Spot("L1-S1", 1, SpotSize.SMALL), Spot("L1-M1", 1, SpotSize.MEDIUM)]),
            Level(2, [Spot("L2-M1", 2, SpotSize.MEDIUM, has_charger=True), Spot("L2-L1", 2, SpotSize.LARGE)])]


def expect_error(fn: Callable[[], object], fragment: str) -> None:
    try:
        fn()
    except ParkingError as e:
        assert fragment in str(e), e
        return
    raise AssertionError(f"expected error containing {fragment!r}")


def main() -> None:
    clock = [datetime(2026, 3, 2, 7, 0, tzinfo=timezone.utc)]
    hourly = HourlyPricing(RATES, timedelta(minutes=15))
    lot = ParkingLot(small_lot(), SmallestFitSelector(), hourly, lambda: clock[0])

    bike = lot.enter(Vehicle("BIKE-1", VehicleType.MOTORBIKE))
    assert bike.spot.id == "L1-S1"
    car = lot.enter(Vehicle("CAR-1", VehicleType.CAR))
    assert car.spot.id == "L1-M1"
    expect_error(lambda: lot.enter(Vehicle("CAR-1", VehicleType.CAR)), "already inside")
    van = lot.enter(Vehicle("VAN-1", VehicleType.VAN))
    assert van.spot.id == "L2-L1"
    lot.enter(Vehicle("CAR-2", VehicleType.CAR))
    expect_error(lambda: lot.enter(Vehicle("CAR-3", VehicleType.CAR)), "no free spot")

    clock[0] += timedelta(minutes=15)
    assert lot.exit(bike.id).fee_cents == 0
    clock[0] += timedelta(minutes=1)
    assert lot.exit(car.id).fee_cents == 200
    clock[0] += timedelta(minutes=59)
    assert lot.exit(van.id).fee_cents == 350
    expect_error(lambda: lot.exit(car.id), "already used")

    ev_lot = ParkingLot(small_lot(), EvAwareSelector(), hourly, lambda: clock[0])
    assert ev_lot.enter(Vehicle("EV-1", VehicleType.CAR, electric=True)).spot.has_charger
    assert not ev_lot.enter(Vehicle("CAR-9", VehicleType.CAR)).spot.has_charger

    peak_clock = [datetime(2026, 3, 2, 8, 30, tzinfo=timezone.utc)]
    peak_lot = ParkingLot(small_lot(), SmallestFitSelector(), PeakPricing(hourly, 150, 8, 10),
                          lambda: peak_clock[0])
    t = peak_lot.enter(Vehicle("CAR-P", VehicleType.CAR))
    peak_clock[0] += timedelta(minutes=120)
    assert peak_lot.exit(t.id).fee_cents == 600

    busy = ParkingLot([Level(1, [Spot(f"M{i}", 1, SpotSize.MEDIUM) for i in range(10)])],
                      SmallestFitSelector(), hourly, lambda: clock[0])

    def arrive(i: int) -> str | None:
        try:
            return busy.enter(Vehicle(f"C{i}", VehicleType.CAR)).spot.id
        except ParkingError:
            return None

    with ThreadPoolExecutor(max_workers=4) as gates:
        results = list(gates.map(arrive, range(20)))
    assigned = [r for r in results if r is not None]
    assert len(assigned) == len(set(assigned)) == 10 and busy.free_spots() == 0
    print("all parking checks passed")


if __name__ == "__main__":
    main()
enum SpotSize { Small = 1, Medium = 2, Large = 3 }

type VehicleType = "MOTORBIKE" | "CAR" | "VAN";
const MIN_SPOT: Record<VehicleType, SpotSize> = { MOTORBIKE: SpotSize.Small, CAR: SpotSize.Medium, VAN: SpotSize.Large };

class ParkingError extends Error {}

interface Vehicle { readonly plate: string; readonly type: VehicleType; readonly electric?: boolean }

class Spot {
  private occupant: string | null = null;
  constructor(readonly id: string, readonly level: number, readonly size: SpotSize, readonly hasCharger = false) {}

  isFree(): boolean { return this.occupant === null; }
  fits(type: VehicleType): boolean { return this.size >= MIN_SPOT[type]; }

  occupy(plate: string): void {
    if (!this.isFree()) throw new ParkingError(`spot ${this.id} is already occupied`);
    this.occupant = plate;
  }

  vacate(): void { this.occupant = null; }
}

interface Level { readonly number: number; readonly spots: readonly Spot[] }
interface Ticket { readonly id: string; readonly vehicle: Vehicle; readonly spot: Spot; readonly entry: Date }
interface Receipt { readonly ticket: Ticket; readonly exit: Date; readonly feeCents: number }

interface SpotSelector {
  /** Picks a free spot that fits, without modifying it. */
  choose(levels: readonly Level[], vehicle: Vehicle): Spot | undefined;
}

class SmallestFitSelector implements SpotSelector {
  choose(levels: readonly Level[], vehicle: Vehicle): Spot | undefined {
    for (const level of levels) {
      const fitting = level.spots.filter((s) => s.isFree() && s.fits(vehicle.type));
      if (fitting.length > 0) return fitting.reduce((a, b) => (b.size < a.size ? b : a));
    }
    return undefined;
  }
}

class EvAwareSelector implements SpotSelector {
  choose(levels: readonly Level[], vehicle: Vehicle): Spot | undefined {
    const rank = (s: Spot): number[] => [s.hasCharger !== !!vehicle.electric ? 1 : 0, s.size, s.level];
    const better = (a: Spot, b: Spot): boolean => {
      const [ra, rb] = [rank(a), rank(b)];
      const i = ra.findIndex((v, k) => v !== rb[k]);
      return i !== -1 && ra[i] < rb[i];
    };
    let best: Spot | undefined;
    for (const s of levels.flatMap((l) => l.spots)) {
      if (s.isFree() && s.fits(vehicle.type) && (!best || better(s, best))) best = s;
    }
    return best;
  }
}

interface PricingPolicy {
  /** Fee in cents. Never negative. */
  feeCents(ticket: Ticket, exit: Date): number;
}

const MINUTE = 60_000;

class HourlyPricing implements PricingPolicy {
  constructor(private readonly centsPerHour: Record<VehicleType, number>, private readonly graceMinutes: number) {}

  feeCents(ticket: Ticket, exit: Date): number {
    const billable = Math.floor((exit.getTime() - ticket.entry.getTime()) / MINUTE) - this.graceMinutes;
    if (billable <= 0) return 0;
    return Math.ceil(billable / 60) * this.centsPerHour[ticket.vehicle.type]; // per started hour
  }
}

class PeakPricing implements PricingPolicy {
  constructor(
    private readonly base: PricingPolicy,
    private readonly multiplierPercent: number,
    private readonly startHourUtc: number,
    private readonly endHourUtc: number,
  ) {}

  feeCents(ticket: Ticket, exit: Date): number {
    const fee = this.base.feeCents(ticket, exit);
    const hour = ticket.entry.getUTCHours();
    const peak = hour >= this.startHourUtc && hour < this.endHourUtc;
    return peak ? Math.floor((fee * this.multiplierPercent) / 100) : fee;
  }
}

// Node runs JavaScript on one thread, and enter/exit never await, so each call is atomic.
class ParkingLot {
  private readonly byPlate = new Map<string, Ticket>();
  private readonly byId = new Map<string, Ticket>();
  private nextTicket = 1;

  constructor(
    private readonly levels: readonly Level[],
    private readonly selector: SpotSelector,
    private readonly pricing: PricingPolicy,
    private readonly now: () => Date,
  ) {}

  enter(vehicle: Vehicle): Ticket {
    if (this.byPlate.has(vehicle.plate)) throw new ParkingError(`${vehicle.plate} is already inside`);
    const spot = this.selector.choose(this.levels, vehicle);
    if (!spot) throw new ParkingError(`no free spot for a ${vehicle.type}`);
    spot.occupy(vehicle.plate);
    const ticket: Ticket = { id: `T${this.nextTicket++}`, vehicle, spot, entry: this.now() };
    this.byPlate.set(vehicle.plate, ticket);
    this.byId.set(ticket.id, ticket);
    return ticket;
  }

  exit(ticketId: string): Receipt {
    const ticket = this.byId.get(ticketId);
    if (!ticket) throw new ParkingError(`unknown or already used ticket ${ticketId}`);
    this.byId.delete(ticketId);
    this.byPlate.delete(ticket.vehicle.plate);
    const now = this.now();
    const feeCents = this.pricing.feeCents(ticket, now);
    ticket.spot.vacate();
    return { ticket, exit: now, feeCents };
  }

  freeSpots(): number {
    return this.levels.flatMap((l) => l.spots).filter((s) => s.isFree()).length;
  }
}

// ---- demo and checks ----
const RATES: Record<VehicleType, number> = { MOTORBIKE: 100, CAR: 200, VAN: 350 };

const smallLot = (): Level[] => [
  { number: 1, spots: [new Spot("L1-S1", 1, SpotSize.Small), new Spot("L1-M1", 1, SpotSize.Medium)] },
  { number: 2, spots: [new Spot("L2-M1", 2, SpotSize.Medium, true), new Spot("L2-L1", 2, SpotSize.Large)] },
];

function check(ok: boolean, what: string): void {
  if (!ok) throw new Error(`FAILED: ${what}`);
  console.log(`ok  ${what}`);
}

function expectError(fn: () => unknown, fragment: string, what: string): void {
  try { fn(); } catch (e) { check(e instanceof ParkingError && e.message.includes(fragment), what); return; }
  check(false, what);
}

let now = new Date("2026-03-02T07:00:00Z");
const advance = (minutes: number): void => { now = new Date(now.getTime() + minutes * MINUTE); };
const hourly = new HourlyPricing(RATES, 15);
const lot = new ParkingLot(smallLot(), new SmallestFitSelector(), hourly, () => now);

const bike = lot.enter({ plate: "BIKE-1", type: "MOTORBIKE" });
check(bike.spot.id === "L1-S1", "motorbike takes the smallest spot on level 1");
const car = lot.enter({ plate: "CAR-1", type: "CAR" });
check(car.spot.id === "L1-M1", "car takes the medium spot on level 1");
expectError(() => lot.enter({ plate: "CAR-1", type: "CAR" }), "already inside", "duplicate plate rejected");
const van = lot.enter({ plate: "VAN-1", type: "VAN" });
check(van.spot.id === "L2-L1", "van goes to the large spot on level 2");
lot.enter({ plate: "CAR-2", type: "CAR" });
expectError(() => lot.enter({ plate: "CAR-3", type: "CAR" }), "no free spot", "full lot rejects entry");

advance(15);
check(lot.exit(bike.id).feeCents === 0, "15 minutes is inside the grace period");
advance(1);
check(lot.exit(car.id).feeCents === 200, "16 minutes costs one hour for a car");
advance(59);
check(lot.exit(van.id).feeCents === 350, "1h15m is exactly one billable hour");
expectError(() => lot.exit(car.id), "already used", "a ticket cannot be used twice");

const evLot = new ParkingLot(smallLot(), new EvAwareSelector(), hourly, () => now);
check(evLot.enter({ plate: "EV-1", type: "CAR", electric: true }).spot.hasCharger, "EV prefers a charger spot");
check(!evLot.enter({ plate: "CAR-9", type: "CAR" }).spot.hasCharger, "non-EV avoids the charger spot");

let peakNow = new Date("2026-03-02T08:30:00Z");
const peakLot = new ParkingLot(smallLot(), new SmallestFitSelector(), new PeakPricing(hourly, 150, 8, 10), () => peakNow);
const t = peakLot.enter({ plate: "CAR-P", type: "CAR" });
peakNow = new Date(peakNow.getTime() + 120 * MINUTE);
check(peakLot.exit(t.id).feeCents === 600, "peak entry pays 150 percent");

const busy = new ParkingLot(
  [{ number: 1, spots: Array.from({ length: 10 }, (_, i) => new Spot(`M${i}`, 1, SpotSize.Medium)) }],
  new SmallestFitSelector(), hourly, () => now);
const arrivals = Array.from({ length: 20 }, (_, i) =>
  Promise.resolve().then(() => busy.enter({ plate: `C${i}`, type: "CAR" }).spot.id));
Promise.allSettled(arrivals).then((results) => {
  const assigned = results.flatMap((r) => (r.status === "fulfilled" ? [r.value] : []));
  check(assigned.length === 10 && new Set(assigned).size === 10 && busy.freeSpots() === 0,
    "concurrent entries: 10 distinct spots assigned, 10 rejected");
});

What to take from this transcript

  • The framework did its job. Every step happened roughly on time, and nothing important was skipped. The wrap-up started at minute 44.
  • Mistakes were survivable because of how they were handled. The vehicle hierarchy, the double and the concurrent-map answer are all common, and each was fixed within a minute, without defensiveness. Their effect on the score was "needed a hint", not "red flag".
  • Hints are part of the interview. "What would the subclasses do differently?" and "would that be enough?" weren't small talk. Learn to hear a question that points at a gap.
  • Extensions teach you about your signatures. Both extensions showed that strategies should receive domain objects rather than fields. It's a lesson worth remembering for every design.

Now try it yourself. Set a 45-minute timer, pick a case study from LLD Interviews, such as the elevator or movie booking, and run through the framework. Afterwards, score yourself against the rubric and check your code against Common LLD Mistakes.

Interview questions

These are follow-ups an interviewer might ask after this design, beyond what the transcript covered.

  1. "How would you handle a lost ticket?" Look up the active ticket by plate, which the activeByPlate map already supports, and charge either the computed fee plus a lost-ticket fee or a fixed daily maximum. It's a new exitWithoutTicket(plate) method on the lot, plus a pricing rule.
  2. "How would you support reservations for a time window?" A Reservation holding a spot, a plate and a window. The selector must skip spots reserved for an overlapping window unless the plate matches. Overlap checks use half-open intervals, as in the edge-cases example.
  3. "How would you show free-spot counts per level on a display board?" Keep counters per level and size, updated inside the same lock as occupy and vacate, and expose them through a read method. If the board must update live, the lot can publish an event after each entry and exit, which is the Observer pattern.
  4. "What if the lot spans several buildings with separate servers?" The in-process lock no longer protects anything. Spot occupancy has to move into shared storage, with an atomic conditional update ("occupy if free") per spot, and ticket uniqueness becomes a unique constraint on active tickets by plate.
  5. "How would you test the concurrent-entry case reliably?" Use more arrivals than spots across a thread pool, then assert that the assigned spots are distinct and that their count equals capacity. It doesn't prove the absence of races, but it catches the common ones. For stronger evidence, add a test-only hook that pauses inside enter to force the interleaving.
  6. "Would you change Spot to use the State pattern if we added 'reserved' and 'out of service'?" Possibly. With four states and transitions that depend on the current state, a state enum with a transition table, or the State pattern, keeps the rules in one place. With only two states, a guarded field is clearer.
  7. "Why does exit remove the ticket before computing the fee?" Under the lock, the order doesn't affect other threads. Removing first makes the "used once" rule obvious in the code: once remove returns the ticket, nothing else can process it. If the fee calculation could fail, you'd compute first and remove after, so a failure leaves the ticket usable.