AlgoViz

Design a parking lot

medium 90 min

Model a car park with several levels as classes: vehicles, spaces of different sizes, tickets and a replaceable price rule.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:48

Parking lot LLD in 90 seconds

1:28Reel coming soon

Design a parking lot in one picture
Design a parking lot in one picture

Theory

Read or listen first. About 2 min.

What it is

A parking lot in a low-level design round is the software at the gates of a car park. It decides which vehicle gets which space, remembers it on a ticket, and at the end turns the time into a price.

Underneath it is a resource allocator: typed things in limited number, a rule who fits where, a claim, a release and a bill. Meeting rooms, hotel rooms, seats and database connections have the same shape.

The answer is small: one coordinator with two verbs, one owner of free spaces, a few records, and one interface for prices. The skill is to see why it is enough.

Why it exists

It is a popular exercise because everybody knows car parks. No time is lost on explaining the domain, so the conversation is about objects from the first minute.

It hides three real difficulties in a friendly picture: classes that differ only in data, prices that change, and two people who want one thing at the same moment. Each appears in systems you will build.

It also shows judgement. The problem can grow without end, with booking, charging, cameras and passes. Choosing what to leave out, and saying so, is part of the answer.

A short history

  1. 1901

    The earliest known multi-storey car park opens in Denman Street, London: seven floors, space for 100 vehicles.

  2. 1935

    The first parking meter is installed in Oklahoma City on 16 July. Time becomes a price, coin by coin.

  3. 1970

    Compare and swap becomes part of the IBM System/370 architecture: change a value only if it is still the expected one, in one instruction.

  4. 1994

    The book Design Patterns describes Strategy and Observer, the two patterns people reach for here.

  5. 2004

    Java 5 brings the concurrency utilities of JSR 166: locks, semaphores, atomic values and concurrent collections.

  6. 2017

    San Francisco's transport agency adopts demand-responsive parking prices on 5 December: a real tariff that changes by place and time.

Words to know

Space or spot
One place for one vehicle, with a size. In code often Spot.
Smallest size
The least size a vehicle fits. Larger ones fit too.
Fallback
Using the next larger size when the best one is out.
Pool or free list
The collection of what is free. Being in it is being free.
Claim
Find and take in one step.
Check then act
Two steps with a gap. Also called time of check to time of use.
Ticket
The unchanging record of one stay: vehicle, space, moment.
Started hour
An hour that has begun counts as a whole one.
Idempotent
Doing it twice has the same result as doing it once.
Invariant
A sentence that is true after every operation, such as free plus taken is total.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

Solve it like an interview

New to it? Start with Approach. Revising? Go straight to the mock.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 3

Vehicle arrives. The smallest free space that fits is claimed, and a ticket is made

Understand it

Start here

A day at Sandy Point

Before any class, look at the thing itself. This small car park by the sea has five spaces: one small (S1), three medium (M1, M2, M3) and one large (L1). Watch what must be remembered, what must be decided, and who decides it.

Sandy Point car park, from empty to full and back
S1M1M2M3L1FREES1M3L1INPAYOUT

Two verbs, enter and leave. Everything else on this page is about doing these two well when many people do them at once.

What an interviewer looks for here

  • Do they ask?

    Sizes, vehicles, prices, number of gates. Each answer changes a class.

  • Do they give each class one job?

    The lot orders the work, the pool owns spaces, the ticket remembers, the policy prices.

  • Do they resist extra classes?

    Vehicle types that differ by one field are an enum. A level that is only a number stays a number.

  • Is one space sold once?

    Finding and taking a space is one step. This is the point most answers miss.

How to spend the round

Code only the two verbs and what they need. Say what you leave out and why.

Questions

Five questions, and what each answer changes

AskIf the answer isThen
How many levels, how many spaces of each size? Can the layout change while it runs?Fixed, known at the startA list of Spot records passed to the constructor
Which vehicles? May a small one use a larger space?Motorcycle, car, bus; yes; a large one never uses a smaller oneAn enum with the smallest size, and a fallback upwards
How is the fee calculated? Per started hour, flat, by size, by time of day? Is there a minimum?Several rules, changingA Pricing interface, injected
One entrance or many?ManyMany threads: claim must be one atomic step
Is payment, a sign, or booking in scope?Payment by someone else's machineA one-method interface; the rest is an extension

Fit

Who fits where

VehicleSmallMediumLargeSpaces
Motorcycleyes, first choiceif no small is freeif no medium either1
Carnoyes, first choiceif no medium is free1
Bus or trucknonoyes1 large here; 5 in a row is an extension
The whole rule is spot.size >= vehicle.minSize, tried from the smallest. Some interviewers say compact instead of medium. The rule stays.

Finding a space for a motorcycle

A car starts at the second question, a bus at the third. One loop covers all three.

Design, first try

The design most people draw first

Every noun becomes a class, every difference a subclass, and the lot does the rest. It works on the whiteboard. Then the second gate opens, the tariff changes, and the electric spaces arrive.

The design to avoid: one class that knows all, and a tree for every noun

ParkingLot- instance: ParkingLot- spots: List<ParkingSpot>- entry: Map<plate, time>+ getInstance()+ park(plate, kind, gate, now): ParkingSpot+ fee(plate, kind): double+ payByCard(number)+ printTicket()+ drawBoard()

1/4The class that does everything

Spaces, prices, cards, printing and the sign in one class. A new tariff, a new card machine and a new sign all change the same file. It is also a Singleton, so two tests share one lot.

usesowns (dies together)has (lives on)extends (is a)

Python
class ParkingLot:                              # everything in one class    def park(self, plate, kind):        for spot in self.spots:                # looks at every space, every time            if spot["free"] and self.fits(kind, spot["size"]):                spot["free"] = False           # a second gate may be here too                self.entry[plate] = datetime.now()                return spot["id"]    def fee(self, plate, kind):        hours = (datetime.now() - self.entry[plate]).seconds / 3600        if kind == "car":            return hours * 2.0                 # floating-point money        elif kind == "bus":            return hours * 5.0        elif kind == "motorcycle":             # the next rule goes here, and here            return hours * 1.0
Before. A scan, a check and an act with a gap between them, floating-point money, a chain of ifs that grows, and .seconds, which silently drops whole days.

Design, better

The design to reach

The design to reach: one coordinator, one owner of free spaces, plain records

ParkingLot- active: Map<id, Ticket>- inside: Set<plate>- lock: Lock+ enter(vehicle): Ticket?+ leave(id): Receipt+ free(): Map<Size, int>

1/6Start from the two verbs

The requirements have two sentences with a verb: a vehicle enters, a vehicle leaves. They become the two methods of one coordinator, ParkingLot. Everything a gate needs is there.

owns (dies together)usesimplementshas (lives on)

A question mark means that the answer may be nothing: a full lot is an ordinary result, not an error.
Python
ticket = lot.enter(Vehicle("RED-1", VehicleType.CAR))   # claims a space, or Nonereceipt = lot.leave(ticket.id)                          # prices, charges, freeslot = ParkingLot(spots, DailyCap(HourlyPricing(rates), 2000), payments, clock)#                       ^ a new rule is a new object passed in, not a new branch
After, seen from a gate. A gate needs two calls. A new price rule is a new object.

Roles

What each class owns

ClassKnowsDoesDoes not know
ParkingLotActive tickets, plates inside, one lockOrders the steps of enter and leaveWhich space is best, how much it costs
SpotPoolFree spaces by sizeClaims and releasesVehicles, tickets, money
SpotIts id, level and sizeNothing: a recordWhether it is free, who is in it
VehiclePlate and typeNothing: a recordWhere it is parked
TicketVehicle, space, entry timeNothing: an unchanging receiptPrices
PricingRatesTurns a ticket and a time into centsSpaces, cards
PaymentsSomebody else's machineCharges once per keyParking

States

The life of a space and of a ticket

A space

Two states in the base design. Closed is a common follow-up: take the space out of the queue and nothing else changes.

A ticket

The base code keeps only active tickets and leaves with the payment in one call. The machine-on-the-wall version, where people pay first and drive out later, needs all of these.

The hard part

Two drivers, one space

Two gates, one free space, the same second. Nobody does anything stupid. Each clerk looks, sees a free space and prints a ticket. The mistake is that looking and taking are two steps.

Asha, Lee and space M3
M1M2M3NORTH1 FREESOUTH1 FREE

The fix is not a faster clerk or a second look. It is one thing that only one hand can hold.

The same second, without a lock

The same second, with one atomic claim

How do you stop two gates from giving out one space?

BreaksCheck, then take
How
if spot.isFree(): spot.park(car) from each gate.
Limit
Both gates can pass the check before either takes. Tests with one thread never see it.
Choose when
Only with a single thread, and even then it is a habit to lose.
WorksOne lock around find and take
How
One lock in the lot, held for the few microseconds of a claim. No payment, no printing inside.
Limit
All gates queue for it. With a handful of gates the queue is nearly always empty.
Choose when
The right first answer. Say the numbers: a car every few seconds against microseconds.
StrongMake taking the check
How
An atomic removal from a free queue, a compare and set on the space, or one conditional update in the database. Whoever wins owns it.
Limit
Covers one space. Two spaces at once, or a space and a plate, still need a lock or a transaction.
Choose when
Many gates, several processes, or a database. Name the one you use and what the loser sees.

Money

Prices as rules, money as whole cents

Strategy is the pattern here: one interface, several rules, chosen from outside. The lot asks for a price and does not care how it was made. That is the open/closed principle at work: open for a new rule, closed for changes in ParkingLot.

Stay in M1 (200 cents an hour)Started hoursHourlyHourly, at most 2000 a dayEvent flat rate
0 minutes1 (the minimum)2002001500
60 minutes12002001500
61 minutes24004001500
130 minutes36006001500
11 hours11220020001500
Ask about the edges aloud: zero minutes, exactly one hour, one minute more.

Started hours without floating point

h=max⁡(1,⌊s+35993600⌋)h(7800)=3h = \max\left(1, \left\lfloor \frac{s + 3599}{3600} \right\rfloor\right) \qquad h(7800) = 3
Adding 3599 before the whole division rounds up. 130 minutes are 7800 seconds: 3 hours, 600 cents.

Do

  • Use enums with data for types that differ by one field
  • Put pricing behind an interface
  • Keep free spaces grouped by size
  • Make find and take one step
  • Store money as whole cents and time as an instant
  • Pass the clock in
  • Agree on the requirements before writing code

Do not

  • Build Car extends Vehicle and CompactSpot extends Spot for one field
  • Let an if chain on vehicle type grow in the fee method
  • Scan every space for every arrival
  • Check in one step and take in another
  • Use floating-point money
  • Call the system clock deep inside
  • Start coding and rewrite when trucks appear

Is it a class at all?

Pool: class. Ticket: record. Size: enum. Level: a number, until it owns something.

Summary

The whole topic in one minute.

Two verbs, enter and leave. One owner of free spaces, grouped by size, where finding is taking. Tickets, vehicles and spaces are records. Prices are a rule that is passed in, in whole cents.

Check plate, claim and store under one short lock. At the exit take the ticket out, charge without a lock, put it back on failure, and release last. Reject classes that hold nothing, and say so.

  • Ask first: levels, sizes, vehicles, prices, gates, and what is out of scope.
  • One job per class: the lot orders the work, the pool owns free spaces, tickets are unchanging records, pricing is a rule.
  • Enums for differences in data. Subclasses only for differences in behaviour.
  • Being in the free queue is being free. Taking a space is the check.
  • Charge before you release. Never hold the lock while you wait for a card.
  • Whole cents, instants in UTC, an injected clock, no Singleton.

Sources