AlgoViz

Design a car rental

hard 90 min

Design the classes of a rental company: search by period, booking a size, handing out a car, upgrades, late returns and bills.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:48

Theory

Read or listen first. About 2 min.

What it is

A car rental system makes promises about the future and keeps them at a counter. A promise is a size, a branch and a period. Keeping it means handing over one real car and getting it back.

Underneath it is capacity over time: a number of equal units, uses with a start and an end, and the question how many are free in between. Hotel rooms of one category, meeting points with equipment and rented tents are the same problem.

Two truths live side by side. The calendar knows how much is promised. The yard knows what is here. The interesting code is where they meet, and where they disagree.

Why it exists

Nearly everybody starts with a flag isAvailable and finds out that it cannot answer anything about next week. The problem teaches that some facts are functions of time.

It contains a small exact algorithm, the peak of overlapping intervals, inside a normal business model. Both have to be right.

The plan is wrong every day: people are late, cars break, flights are cancelled. A design that says so clearly is worth more than one that assumes the plan.

A short history

  1. 1906

    The earliest known offer of cars for rent.

  2. 1916

    Joe Saunders of Omaha starts with one borrowed Ford Model T. A year later the company rents out 18 of them, for 10 cents a mile.

  3. 1918

    Walter L. Jacobs opens a rental business in Chicago with twelve Ford Model T. John Hertz buys it in 1923.

  4. 1946

    Warren Avis founds a car rental company in Ypsilanti, Michigan.

  5. 1964

    SABRE, the reservation system of American Airlines and IBM, is launched: capacity over time, for seats, on a computer.

  6. 2000

    Zipcar is founded in Cambridge, Massachusetts: cars by the hour, for members.

Words to know

Period
From a start to an end. The end is not included.
Use
A period in which one unit is away, cleaning included.
Peak
The largest number of uses at the same moment.
Turnaround
Time between return and next hand-over.
Shelf
One branch and one size: the thing that has a count.
Late assignment
Choosing the car at pick-up instead of at booking.
Upgrade
A bigger car for the price of the smaller.
Fragmentation
Free time in pieces that are too short to use.
Write skew
Two transactions read the same, write different rows, and break a rule together.
Hold
Money promised by a card and not yet taken.

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

Promise. Count the peak in the period and add the booking in one step

Understand it

Start here

A day at the pond

Three boats, five people, one board
BOATS9121518smallsmallbigF1S1S2Two small boats,one big boat.

The board counts. The jetty hands out. Keep these two apart and the rest is easy.

What an interviewer looks for here

  • Availability is about a period

    The boolean on the car is the classic mistake. The answer is a count over time.

  • Promise and assignment

    Selling a size and handing out a car are two moments. Seeing that is half of the problem.

  • A real lifecycle

    Booked, out, returned, cancelled, and which verb is allowed when.

  • The last one

    Two clicks, one car. Count and add must be one step.

  • The world disagrees

    Late, broken, never picked up. A design that assumes the plan is true fails in its first week.

  • Money with care

    Price fixed at the promise, late fee by rule, charge with a key.

Questions

Six questions, and what each answer changes

AskIf the answer isThen the design has
Do customers book a car or a kind of car?A kind, for example familyCounting by size; the car joins at pick-up
Is the return at the same branch?Yes, at firstA constant fleet for each branch
What lies between two rentals?An hour of cleaningA turnaround added to every use
What if nothing of that size is there?A bigger one for free, if possibleUpgrade upwards, with a check
How is the price made?By started day, fixed at bookingPricing, and rent stored in the booking
Is the card charged at booking?At the endReturn first, then collect with a key

Counting

How many are free?

Two small cars. Four bookings overlap the wish from 10 to 16. Is it sold out? Not necessarily: what counts is how many are in use at the same moment.

Without turnaround. The peak is 2, so none of two is free

MomentA 9 to 11B 11 to 13C 12 to 15D 15 to 18In use
10 (wish begins)x1
11 (B begins)x1
12 (C begins)xx2
15 (D begins)x1
Without C the peak is 1 and the wish fits, although three bookings overlap it.

Free units for a wish

free=n−max⁡m∈M#{ b:sb≤m<eb },M={sw}∪{ sb:sw<sb<ew }\text{free} = n - \max_{m \in M} \#\{\,b : s_b \le m < e_b\,\}, \qquad M = \{s_w\} \cup \{\, s_b : s_w < s_b < e_w \,\}
n is the fleet, s and e are start and end with the turnaround included. The number in use rises only where a use begins, so these moments are enough.

From a wish to a promise

From the key to the calendar everything is under one lock.

Design, first try

The design most people draw first

A system class, an abstract vehicle with a flag, an abstract user. It looks complete, and it cannot answer whether a car is free next Tuesday.

The design to avoid: the car knows its bookings, and a tree for every noun

CarRentalSystem- instance: CarRentalSystem- cars, users, bookings+ searchCar(), rentCar()+ returnCar(), pay(), email()

1/4One class that rents, prices and emails

A global instance with every verb. Tests cannot have their own, and two branches cannot have different rules.

owns (dies together)extends (is a)

Three questions are mixed: what is promised, which car is handed out, and what it costs.
Python
def rent_car(self, user, car, days):    if car.is_available:                  # available when?        car.is_available = False          # two clicks pass the check together        price = days * car.price        self.card.charge(user, price)     # fails: the car is blocked for ever        return Booking(user, car, price)
Four mistakes: a flag for a period, a check and an act with a gap, a side effect before the charge, and a car instead of a size.

Design, better

The design to reach

The calendar counts promises by branch and size. The yard, which is the two maps of ready and cleaning cars, knows what stands here. The booking lives through its states and gets its car at pick-up. Prices are a rule.

The design to reach: a calendar of promises, a yard of cars, a rule for prices

RentalService- ready: Map<Shelf, Queue<Car>>- cleaning: Map<plate, Car>- byKey, lock+ available(branch, period)+ book(key, ...): id+ cancel(id)+ pickUp(id): Car+ giveBack(id): Invoice

1/6Five verbs

Look, promise, take back the promise, hand out, take in. The desk and the website call these and nothing else.

owns (dies together)has (lives on)usesimplementsdepends on

Two truths that must not be mixed: the calendar knows the future in numbers, the yard knows the present in cars.

Roles

What each class owns

ClassKnowsDoes not know
CalendarHow many are promised whenPlates, prices, customers
RentalServiceBookings, what is ready, who may do what nowHow a price is made
BookingWhat was sold, and how far it has comeOther bookings
PeriodWhether two periods overlapWhat they are for
PricingRent and late feeStates, cars
CarPlate, size, branchWhether it is free

States

The life of a booking and of a car

A booking

Paying is not a state here. An invoice can be open long after the car is back.

A car

The states of a car are the collections it is in. No field can disagree with them.

The hard part

Two clicks, one car

Asking and promising as two steps

Both answers were true when they were given.

Asking and promising as one step

The second person gets a useful no.

How do you stop two customers from getting the last car?

BreaksCheck on the search page
How
The page shows 1 free, the click books.
Limit
Seconds or minutes lie between look and click.
Choose when
Never. The page is advice.
WorksOne lock around count and add
How
As in the code: the count under the lock is the one that decides.
Limit
All branches wait for each other for microseconds.
Choose when
The right first answer.
StrongThe smallest lock that holds the rule
How
A lock for each branch and size, or in a database a conditional update on a counter row for each day.
Limit
Moves between sizes need two locks, in a fixed order.
Choose when
Many branches, several processes. Say the numbers first.

Bills

When each amount is fixed

Whole cents, started days and hours

Small boat, 4000 a dayTime awayRentLateTotal
9:00 to 17:00, back at 17:008 h400004000
Back at 17:3030 min late40000 (grace)4000
Back at 17:3131 min late400010005000
Back at 20:103 h 10 late40004000 (four hours)8000
Back at 22:305 h 30 late40004000 (cap)8000
Booked 25 hours25 h8000 (two days)08000

Do

  • Promise a size, choose the car at pick-up
  • Use periods without their end
  • Count the peak, not the overlaps
  • Add cleaning to every use
  • Treat a late car as busy now
  • Check the calendar before an upgrade
  • Fix the rent in the booking
  • Record the return before the charge

Do not

  • Put isAvailable on a car
  • Build EconomyCar and LuxuryCar
  • Trust the search page
  • Give away a car because it stands there
  • Compute rent again at the end
  • Let a declined card block a return
  • Use the calendar date as a day
  • Write 16:59:59

Which part changes?

Summary

The whole topic in one minute.

A booking promises a size for a period and stores its rent. Free is fleet minus the peak of uses, each widened by the cleaning time, and the peak is found at the starts. Count and add are one step.

At pick-up a ready car is chosen, upwards if needed and only if the calendar agrees. Late cars are busy now, early returns free the rest, a return is final before any money moves.

  • Available is a question about a period. The answer is fleet minus the peak of uses in it.
  • A booking promises a size. The car is chosen at pick-up, from what is ready.
  • Periods exclude their end; two overlap if each starts before the other ends.
  • Count and add in one step. The search result is advice.
  • Plan and world differ: late is busy now, early return frees the rest, returned is not ready.
  • An upgrade needs a free promise and a ready car.
  • Rent is fixed at booking, the late fee is a rule with a cap, the return never waits for money.

Sources