AlgoViz

Design a meeting room scheduler

medium 80 min

Book a room for a slot, a number of people and some equipment, without ever booking one room twice: half-open slots, a sorted calendar for each room, rules that can be added, one lock, and then repeats, time zones and empty rooms.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:39

Theory

Read or listen first. About 2 min.

What it is

A meeting room scheduler takes a wish (a time, a number of people, some equipment) and gives a room, or says that none is free. People can cancel, move, and ask for the next free time.

Under the surface it is an interval problem. Each booking is a pair of numbers, and for each room the pairs must never overlap. Everything else, such as which room is best and who may book, is a decision that changes while this rule stays.

As an object design it is small: one coordinator, one calendar for each room that owns the rule, a few values, and interfaces in front of the two decisions.

Why it exists

It is asked because it can be answered at every level. A beginner can get a working overlap test. An experienced engineer finds the race, the failed move, the clock change, and the place where a database takes over.

The same shape is in hotel rooms, cars for rent, operating theatres, delivery windows and machines in a factory. Whoever has understood one rail with blocks has understood them all.

It also shows in one example why an invariant is worth money: because a calendar never holds overlaps, finding a conflict needs two looks and no clever tree.

A short history

  1. November 1998

    RFC 2445 describes iCalendar, a common text format for events, repeats and busy times, written by authors from Lotus and Microsoft.

  2. September 2009

    RFC 5545 replaces it and is still the base of calendar exchange. It defines RRULE, EXDATE, RECURRENCE-ID and VFREEBUSY.

  3. September 2010

    PostgreSQL 9.0 adds exclusion constraints: uniqueness with any comparison, such as "overlaps".

  4. 10 September 2012

    PostgreSQL 9.2 adds range types. Together with exclusion constraints, "no two bookings of a room overlap" becomes one line of a table.

Words to know

Slot
A start and an end. The start is inside, the end is not.
Half open
Written [start, end). Touching slots do not overlap.
Conflict
A booking that overlaps the wish.
Invariant
A sentence that is true after every call.
Gap
Free time between two bookings, or at the edge of a window.
Check then act
Deciding on an answer that may be old when the action happens.
Interval tree
A search tree where each node also knows the greatest end below it. Finds overlaps among overlapping entries.
Series
A rule for repeated meetings, with exceptions.
Grace
Minutes after the start before an unused booking runs out.
Exclusion constraint
A database rule that forbids two rows for which all given comparisons are true.

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

A wish arrives. Rules may refuse it, and rooms are put in order

Understand it

Story

A morning in the practice rooms

A music school has three practice rooms. Beside each door hangs a wooden rail with the hours of the morning, and a booking is a wooden block that slides onto the rail. Two blocks cannot be in the same place. Our program must give the same promise, with many hands reaching for the rails at once.

Blocks on a rail
ATTIC2 chairs101112BLUE4 chairs101112CELLAR9 chairs1011129:00

The blocks are bookings, the rails are calendars, and the pair of hands is the lock.

What an interviewer looks for here

  • Time done right

    Half-open slots, one overlap test, and a word about time zones.

  • One owner of the rule

    Exactly one object can break or keep the promise that bookings do not overlap.

  • Look and take together

    No public check before the booking.

  • Room for new wishes

    Best room, longest stay, equipment: added beside the code and not inside it.

How to spend the round

Ask first

Five questions, and what each answer changes

QuestionIf yesIf noDefault we take
Does the caller choose the room?book_room(room, slot)The system picks, so we need an orderThe system picks
Do rooms differ?Seats and features, filter before searchAny free room will doThey differ
Any start time, or fixed blocks?Intervals and a sorted listA bitmap for each day is enoughAny minute
Do people's own calendars matter?Find a common free time firstOnly rooms can be busyOnly rooms, people as an extension
Do meetings repeat?Series, exceptions, time zonesSingle bookingsSingle, repeats as an extension
Read the defaults back in one sentence, and ask whether that is the scope.

Time

When do two slots overlap?

Write a slot as start and end, with the start inside and the end outside: [start, end). Mathematicians call this half open. It has three pleasant effects. Slots that touch do not overlap. The length is end - start. A day splits into slots with no gap and no minute counted twice.

The overlap test

overlap(a,b)  ⟺  astart<bend;∧;bstart<aend\text{overlap}(a, b) \iff a_{start} < b_{end} ;\wedge; b_{start} < a_{end}
It is easier to see from the other side: they do not overlap when a ends before b starts, or b ends before a starts. The test is the opposite of that.

Booked: 10:00 to 11:00. Is the wish in the way?

Wisha.start < b.endb.start < a.endOverlap
09:00 to 10:00yesnoNo, it touches
09:30 to 10:30yesyesYes, over the start
10:15 to 10:45yesyesYes, inside
09:00 to 12:00yesyesYes, around it
10:30 to 11:30yesyesYes, over the end
11:00 to 12:00noyesNo, it touches
a is the booking, b is the wish. People who write four separate cases usually forget the third or the fourth one that says yes.

Two looks are enough in a sorted calendar

This only works because the calendar never holds an overlap. The invariant pays for the speed.

Bad

The design most people draw first

Every noun becomes a class and every difference a subclass. The picture looks complete, and it has the race in its method names.

The design to avoid: rooms that guard themselves, and a check outside

BookingManager- allBookings: List<Booking>+ isAvailable(room, from, to)+ book(room, user, from, to)«abstract»Room+ isFree: boolean+ slots: boolean[24]+ setFree(value)

1/4A manager and a room

isAvailable and book are two public calls. Between them another thread can book. The bug is in the signature, before any code is written.

usesextends (is a)owns (dies together)

Python
class BookingManager:    def is_available(self, room, start, end):        for b in self.all_bookings:            if b.room == room and b.start <= start and end <= b.end:   # only "inside" is found                return False        return True                                                    # true for how long?    def book(self, room, user, start, end):        self.all_bookings.append(Booking(room, user, start, end))      # trusts the caller
Three bugs in ten lines.
  1. 1

    Four overlaps, one found

    A wish from 9:30 to 10:30 is not inside the booking from 10 to 11, so it is let through.

  2. 2

    The check is outside

    book believes that somebody asked. Two callers ask, both hear yes, both book.

  3. 3

    Every room's history is read

    All bookings of all rooms since the school opened are in one list, and each question walks through it.

Good

The design to reach

The design to reach: one door, one calendar for each room, rules beside it

Scheduler- bookings: Map<Id, Booking>- lock+ book(request): Booking?+ move(id, who, slot): Booking?+ cancel(id, who)+ first_free(request, window)

1/6Start with the verb

Somebody wants to book. One object takes that call, and it is the only public door.

has (lives on)implementsowns (dies together)

Yellow holds the invariant, purple coordinates, blue and green change with the school's wishes.

Who knows what

What each class owns

ClassKnowsDoesDoes not
SlotStart and endTests overlapKnow a room or a date format
RoomSeats and featuresNothingKnow whether it is free
RequestA wishNothingHave an id
BookingA promiseNothingChange after it is made
RoomCalendarBookings of one roomFinds conflicts and gapsLock, or choose
RoomChoiceA tasteOrders roomsSee calendars
BookingRuleOne limitRefuses with a reasonSee other rules
SchedulerEverything aboveCoordinates under a lockCompare times itself

Life

The life of a booking

A booking

The first version needs only Booked and gone. The rest arrives with check-in, on the page about empty rooms.

Race

Two people, one room

Both look, both book

One step

How do you stop two people from booking one room?

BreaksAsk first, then book
How
if is_available(...): book(...).
Limit
The answer is old the moment it is given. A shorter gap makes the bug rarer and harder to find.
Choose when
Only for showing a screen, never for deciding.
WorksOne lock around look and place
How
book finds and adds inside one critical section.
Limit
One process. All rooms wait for each other, for microseconds.
Choose when
The interview answer, and one office.
StrongLet the store refuse overlaps
How
A database constraint that forbids two overlapping ranges for one room, and a retry with the next room.
Limit
Needs a store that knows ranges. A plain unique index does not.
Choose when
More than one process.

Shape

Is it a class at all?

Ask this about every noun

Grows without pain

  • A rule is a class with one method
  • Equipment is a set of words
  • One calendar for each room
  • Time comes in as an argument

Hurts at the second wish

  • if user.is_teacher inside book
  • PianoRoom, DrumRoom, both
  • One list of all bookings
  • datetime.now() in the middle

Summary

The whole topic in one minute.

Protect one promise: for each room, bookings never overlap. Give it to one class, RoomCalendar, sorted by start. Because the promise holds, the left and the right neighbour decide about a conflict.

Scheduler is the only door. It asks rules and room choice outside the lock, and looks and places inside it. A move takes out, looks, and puts in or puts back.

The rest is extension: a series is a rule with exceptions, expanded in local time and compared in UTC. Common time is merged busy slots. An unused booking runs out by comparison. Two servers share a constraint in the database.

  • Slots are half open. Overlap is two strict comparisons joined by and.
  • A calendar that never holds overlaps needs two looks to find a conflict.
  • Look and place are one step under one lock. There is no public check.
  • Full is an answer. A broken rule is an error with a reason.
  • Moving takes the old slot out before it looks, and puts it back if it fails.
  • Which room and who may book are the parts that change, so they stand behind interfaces.

Sources