SyntaxPilot
Courses/Low-Level Design/Lesson 82
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 82 of 90

Design a meeting room scheduler and calendar

meeting scheduler requirementsRoomMeetingIntervaloverlap detectionTreeMap for intervalsroom allocation strategyrecurring meetingsinvites and RSVPconflicts and notifications

These are the notes for Low-Level Design (LLD) episode 82: designing a meeting room scheduler and calendar, the system an office uses to book rooms so that two meetings never land in the same room at the same time. We cover the meeting scheduler requirements, the main classes (Room, Meeting, Interval), overlap detection, a TreeMap for intervals, a swappable room allocation strategy, recurring meetings, invites and RSVP, and conflicts and notifications.

How the code was run: every program was saved as Main.java in a fresh folder and run with javac Main.java && java -cp . Main on OpenJDK 21. Every output below is the real output, pasted exactly. People, rooms, meetings and times are made up. Nothing here describes how any real calendar product is built.

1. The problem: the sign-up sheet on the board room door

An office has a paper sheet taped to the board room door. You write your meeting and time slot on it: "Design review, 10:30 to 11:00". At 10 am two teams walk in, both sure they booked 10 to 12. Somebody read the sheet wrong: a double booking. Meanwhile four people sit in the 40-seat hall and a team of thirty has nowhere to go. People keep asking "can you come?" and getting "maybe", and there's a stand-up every single morning. A meeting room scheduler is that sheet, on a computer, for every room in the building.

Real life In the design
The board room, 12 chairs A Room with a name and a capacity
"10:30 to 11:00" written on the sheet An Interval (start, end)
"Design review, Priya, board room, 10:30 to 11:00, with Rahul" A Meeting
Two teams at 10 am, one room Overlap detection must catch it
Reading the sheet in time order A TreeMap sorted by start time
Four people in the 40-seat hall A room allocation strategy
"Stand-up, every day at 9:30" A recurring meeting
"Can you come?" "Maybe." An invite and its RSVP
A note slipped under your door A notification

2. Requirements and the main classes

Meeting scheduler requirements are the list of things the system must do. Ours, kept small enough for a machine-coding round:

  1. Book a room for a time slot.
  2. Never put two meetings in one room at the same time.
  3. Pick a room that fits the number of people.
  4. Book meetings that repeat (daily, weekly).
  5. Invite people; each person replies (accept, decline, maybe), and people are warned about clashes in their own calendar.
  6. Tell people about every change (notifications).

The classes:

  • Room: a name and a capacity (the number of seats). Example: new Room("Board", 12).
  • Interval: a stretch of time with a start and an end. Example: 10:30 to 11:00.
  • Meeting: a title, an organiser (the person who sets it up), a room, an interval and the attendees (the people invited).

To keep the numbers simple, a time is minutes after midnight: 10:30 is 10 × 60 + 30 = 630, 11:00 is 660, 15:00 is 900. Later, for recurring meetings, we switch to real dates with LocalDateTime.

3. Attempt 1: "does it start inside a booking?"

Our first idea for a clash check: a new meeting clashes if its start falls inside an existing booking.

import java.util.*;
record Room(String name, int capacity) {}
record Meeting(String title, Room room, int start, int end) {}   // minutes after midnight
class Calendar {
    final List<Meeting> booked = new ArrayList<>();
    boolean book(Meeting m) {
        for (Meeting b : booked)            // attempt: "does it START inside a booking?"
            if (b.room().equals(m.room()) && m.start() >= b.start() && m.start() < b.end())
                return false;
        booked.add(m);  return true; } }
public class Main {
    static int at(int h, int m) { return h * 60 + m; }
    static String hm(int t) { return String.format("%02d:%02d", t / 60, t % 60); }
    public static void main(String[] args) {
        Room board = new Room("Board", 12);  Calendar cal = new Calendar();
        List<Meeting> asks = List.of(new Meeting("Design review", board, at(10, 30), at(11, 0)),
            new Meeting("Sprint planning", board, at(10, 0), at(12, 0)),
            new Meeting("One-on-one", board, at(10, 45), at(11, 15)),
            new Meeting("Budget call", board, at(15, 0), at(14, 0)));    // ends before it starts!
        for (Meeting m : asks) System.out.println(m.title() + " "
            + hm(m.start()) + "-" + hm(m.end()) + " booked: " + cal.book(m));
        System.out.println("Board room now has " + cal.booked.size() + " meetings");
    } }

Real output:

Design review 10:30-11:00 booked: true
Sprint planning 10:00-12:00 booked: true
One-on-one 10:45-11:15 booked: false
Budget call 15:00-14:00 booked: true
Board room now has 3 meetings

Why it failed

  • Sprint planning, 10:00 to 12:00: booked: true, while the design review (10:30 to 11:00) sits right inside it. Sprint planning starts before the review and ends after it: it doesn't start inside the review, it swallows it. The check only looked at the start.
  • The one-on-one (10:45 to 11:15) was refused correctly: its start is inside the review.
  • Budget call 15:00 to 14:00: booked: true. It ends before it starts. Nobody checked that start < end.
  • record Meeting(...) is a record: a short Java class for plain data, with the constructor, getters (m.start()), equals and toString written for you.
  • String.format("%02d:%02d", ...) prints a number with at least 2 digits, padded with a zero: 9 becomes 09.

4. Overlap detection and half-open intervals

Overlap detection is deciding whether two time intervals share any time. One rule catches every case:

Two intervals a and b overlap when a.start < b.end && b.start < a.end.

Read it as: "a starts before b ends, and b starts before a ends". Check it against every shape:

Case a b a.start < b.end b.start < a.end Overlap?
b inside a (the bug) 10:00-12:00 10:30-11:00 600 < 660 yes 630 < 720 yes yes
a inside b 10:30-11:00 10:00-12:00 630 < 720 yes 600 < 660 yes yes
across the end 10:45-11:15 10:30-11:00 645 < 660 yes 630 < 675 yes yes
across the start 10:00-10:45 10:30-11:00 600 < 660 yes 630 < 645 yes yes
just touching 11:00-11:15 10:30-11:00 660 < 660 no no
apart 14:00-15:00 10:30-11:00 840 < 660 no no

A half-open interval, written [start, end), includes its start minute and excludes its end minute. So 10:00-11:00 and 11:00-12:00 just touch: one ends at the exact minute the other begins, and both can be booked in the same room. That's what people expect from a calendar. The strict < in the rule is what makes intervals half-open.

The second fix: an Interval that refuses bad data. A record can have a compact constructor, Interval { ... }, which runs checks before the fields are set. If start >= end, it throws an IllegalArgumentException, Java's exception for "this argument is not acceptable". Bad data never gets into the system.

5. A TreeMap for intervals: check 2 neighbours, not 10,000

A busy room has thousands of bookings a year. Checking a new meeting against every booking one by one (a linear scan) costs one check per booking: 10,000 bookings, 10,000 checks, for every new request.

The paper sheet has the answer: it's sorted by time. You only look at the meeting just before your slot and the one just after.

  • A TreeMap is a Java map that keeps its keys in sorted order. Ours maps start time → interval. Finding, adding and removing a key takes O(log n) steps: about 14 steps for 10,000 keys (2¹⁴ = 16,384), because it is a balanced tree that halves the search each step. O(log n) ("order log n") is Big-O notation for "grows like the logarithm of n": doubling the bookings adds just one more step.
  • floorEntry(t): the entry with the greatest key ≤ t, the last meeting that starts at or before t.
  • ceilingEntry(t): the entry with the smallest key ≥ t, the first meeting that starts at or after t. Both return null when there is none.

Why two neighbours are enough: the booked meetings in one room never overlap each other (we never let them). So sorted by start, they are also sorted by end. Any meeting that starts before our floor neighbour also ends before the floor neighbour starts, so it can't reach our new slot. And if the ceiling neighbour starts at or after our end, every later meeting does too. So if neither neighbour overlaps, nothing does.

import java.util.*;
record Interval(int start, int end) {            // [start, end): the end minute is not included
    Interval { if (start >= end)
        throw new IllegalArgumentException("start " + start + " must be before end " + end); }
    boolean overlaps(Interval o) { return start < o.end && o.start < end; } }
class RoomCalendar {
    private final TreeMap<Integer, Interval> byStart = new TreeMap<>();   // sorted by start
    int checks = 0;
    boolean book(Interval iv) {
        var before = byStart.floorEntry(iv.start());     // the last one starting at or before
        var after = byStart.ceilingEntry(iv.start());    // the first one starting at or after
        checks += 2;                                     // only two neighbours, never all
        if (before != null && before.getValue().overlaps(iv)) return false;
        if (after != null && after.getValue().overlaps(iv)) return false;
        byStart.put(iv.start(), iv);  return true; } }
public class Main { public static void main(String[] args) {
    RoomCalendar board = new RoomCalendar();
    System.out.println("Design review 10:30-11:00: " + board.book(new Interval(630, 660)));
    System.out.println("Sprint planning 10:00-12:00: " + board.book(new Interval(600, 720)));
    System.out.println("One-on-one 10:45-11:15: " + board.book(new Interval(645, 675)));
    System.out.println("Stand-up 11:00-11:15: " + board.book(new Interval(660, 675)));
    RoomCalendar busy = new RoomCalendar();                 // 10,000 half-hour meetings
    for (int i = 0; i < 10_000; i++) busy.book(new Interval(i * 60, i * 60 + 30));
    busy.checks = 0;  busy.book(new Interval(599_980, 599_990));
    System.out.println("10,000 booked, checks for one more: " + busy.checks);
    new Interval(900, 840);                                 // Budget call 15:00-14:00
} }

Real output:

Design review 10:30-11:00: true
Sprint planning 10:00-12:00: false
One-on-one 10:45-11:15: false
Stand-up 11:00-11:15: true
10,000 booked, checks for one more: 2
Exception in thread "main" java.lang.IllegalArgumentException: start 900 must be before end 840
    at Interval.<init>(Main.java:4)
    at Main.main(Main.java:26)
  • Sprint planning and the one-on-one are now refused. The stand-up (11:00 to 11:15) touches the review and is booked: half-open intervals at work.
  • With 10,000 half-hour meetings booked, one more booking needed just 2 checks. A list scan would have needed 10,000.
  • new Interval(900, 840) (the 15:00-14:00 budget call) throws: start 900 must be before end 840.
  • var lets Java work out a local variable's type: here Map.Entry<Integer, Interval>.
  • 10_000: underscores in a number are just for reading; it is 10000.

6. Room allocation strategy

People often don't care which room. They say "we are four, find us a room". A room allocation strategy is the rule that picks the room. Our building: Hall (40 seats), Board (12), Huddle (4).

  • Attempt: the first free room that is big enough.
  • Fix: smallest fit, the smallest free room that still fits everyone, so big rooms stay free for big teams.

We make it an interface from the start, so each rule is its own class and they can be swapped: the Strategy pattern (episode 34).

import java.util.*;
record Room(String name, int capacity) {}
interface RoomAllocationStrategy { Optional<Room> pick(List<Room> free, int people); }
class FirstFreeRoom implements RoomAllocationStrategy {      // first room that is big enough
    public Optional<Room> pick(List<Room> free, int people) {
        return free.stream().filter(r -> r.capacity() >= people).findFirst(); } }
class SmallestFitRoom implements RoomAllocationStrategy {    // smallest room that is big enough
    public Optional<Room> pick(List<Room> free, int people) {
        return free.stream().filter(r -> r.capacity() >= people)
                   .min(Comparator.comparingInt(Room::capacity)); } }
public class Main { public static void main(String[] args) {
    List<Room> rooms = List.of(new Room("Hall", 40), new Room("Board", 12), new Room("Huddle", 4));
    for (RoomAllocationStrategy s : List.of(new FirstFreeRoom(), new SmallestFitRoom())) {
        List<Room> free = new ArrayList<>(rooms);                 // 9:00 to 10:00, all free
        System.out.println(s.getClass().getName() + ":");
        for (int people : new int[] {4, 30}) {
            Optional<Room> r = s.pick(free, people);
            r.ifPresent(free::remove);
            System.out.println("  " + people + " people -> " + r.map(Room::name).orElse("no room"));
        } } } }

Real output:

FirstFreeRoom:
  4 people -> Hall
  30 people -> no room
SmallestFitRoom:
  4 people -> Huddle
  30 people -> Hall
  • First free room gives the 4 people the Hall, so the team of 30 gets no room.
  • Smallest fit gives the 4 people the Huddle and the 30 people the Hall.
  • Optional<Room> is a box that holds a room or is empty ("no room"); orElse("no room") takes the value or a default. r.ifPresent(free::remove) removes the room only when there is one.
  • free::remove is a method reference: shorthand for room -> free.remove(room).
  • Comparator.comparingInt(Room::capacity) compares rooms by capacity, so min finds the smallest.
  • Other strategies you could add: "closest to the organiser's floor", "a room with a video screen", "spread meetings evenly". Each is one new class.

7. Recurring meetings: all or nothing

A recurring meeting repeats on a rule: "every day at 9:30, 5 times, from Monday". Each date in the series is an occurrence. We use real dates now:

  • LocalDateTime: a date plus a time with no time zone, for example 2026-11-16T09:30. plusDays(1) gives the next day.
  • Duration: a length of time: Duration.ofMinutes(15).
  • LocalDateTime values compare in time order, so they work as TreeMap keys. isAfter and isBefore compare two of them.

Attempt: book each occurrence one by one and skip a day that clashes. Fix: check every occurrence first, then book all of them, or none, and return the clashing dates so the organiser can choose another time. "All or nothing" is the same idea a database calls an atomic operation.

import java.time.*;  import java.util.*;
record Recurrence(int everyDays, int count) {              // "every 1 day, 5 times"
    List<LocalDateTime> starts(LocalDateTime first) {
        List<LocalDateTime> out = new ArrayList<>();
        for (int i = 0; i < count; i++) out.add(first.plusDays((long) i * everyDays));
        return out; } }
class Room {  final TreeMap<LocalDateTime, LocalDateTime> booked = new TreeMap<>();  // start -> end
    boolean free(LocalDateTime s, LocalDateTime e) {
        var before = booked.floorEntry(s);  var after = booked.ceilingEntry(s);
        return (before == null || !before.getValue().isAfter(s))
            && (after == null || !after.getKey().isBefore(e)); }
    int bookEachDay(LocalDateTime first, Duration len, Recurrence r) {    // attempt: one by one
        int n = 0;
        for (var s : r.starts(first)) if (free(s, s.plus(len))) { booked.put(s, s.plus(len)); n++; }
        return n; }
    List<LocalDate> bookSeries(LocalDateTime first, Duration len, Recurrence r) {  // all or nothing
        List<LocalDate> clashes = new ArrayList<>();
        for (var s : r.starts(first)) if (!free(s, s.plus(len))) clashes.add(s.toLocalDate());
        if (clashes.isEmpty()) for (var s : r.starts(first)) booked.put(s, s.plus(len));
        return clashes; } }
public class Main { public static void main(String[] args) {
    var call = LocalDateTime.of(2026, 11, 18, 9, 30);         // a client call on Wednesday
    var standup = LocalDateTime.of(2026, 11, 16, 9, 30);      // Monday, 9:30, 15 minutes
    var daily5 = new Recurrence(1, 5);  var q = Duration.ofMinutes(15);  Room a = new Room(), b = new Room();
    for (Room r : List.of(a, b)) r.booked.put(call, call.plusMinutes(30));
    System.out.println(standup.getDayOfWeek() + ", one by one: " + a.bookEachDay(standup, q, daily5) + " of 5");
    System.out.println("Series 9:30, clashes: " + b.bookSeries(standup, q, daily5));
    System.out.println("Series 10:00, clashes: " + b.bookSeries(standup.plusMinutes(30), q, daily5)
        + ", room b has " + b.booked.size() + " bookings"); } }

Real output:

MONDAY, one by one: 4 of 5
Series 9:30, clashes: [2026-11-18]
Series 10:00, clashes: [], room b has 6 bookings
  • 16 November 2026 is a MONDAY (printed by Java itself with getDayOfWeek()).
  • One by one booked 4 of 5: the stand-up series has a hole on Wednesday, the 18th, and nobody was told.
  • The series method reports the clash, [2026-11-18], and books nothing.
  • At 10:00 there are no clashes: the room has 6 bookings, the client call plus 5 stand-ups.
  • free(s, e) is the same two-neighbour check as section 5, written with dates: the floor neighbour must end at or before s, and the ceiling neighbour must start at or after e.
  • A real system stores the rule (every 1 day, 5 times; or "every Monday until March") instead of copying meetings forever, and expands occurrences when it needs them. A series that never ends can't be expanded in full, so it's checked a few months ahead.

8. Invites, RSVP, conflicts and notifications

  • An invite asks a person to a meeting.
  • An RSVP is their reply. The letters come from the French "répondez s'il vous plaît": please reply. The reply is PENDING until they answer, then ACCEPTED, DECLINED or TENTATIVE ("maybe").
  • We keep replies in an enum: a Java type with a fixed list of values. Only those four replies can exist, so a typo like "acepted" is a compile error, not a silent bug.
  • Notifications: sending mails or phone alerts is not the scheduler's job. A Notifier interface is told about every change, and anyone can plug one in: the Observer pattern (episode 35). The scheduler is the subject; notifiers are observers.
  • Conflicts for people: if a person already accepted a meeting at that time, the invite warns them. A room clash is refused; a person clash is only a warning, because people decide for themselves.
import java.util.*;
enum Rsvp { PENDING, ACCEPTED, DECLINED, TENTATIVE }
interface Notifier { void send(String to, String message); }    // Observer: hears every change
record Slot(String title, int start, int end) {
    boolean overlaps(Slot o) { return start < o.end && o.start < end; } }
class Scheduler {
    final Map<String, List<Slot>> accepted = new HashMap<>();   // person -> meetings accepted
    final Map<String, Rsvp> rsvps = new LinkedHashMap<>();
    final List<Notifier> notifiers = new ArrayList<>();
    void tell(String to, String msg) { for (Notifier n : notifiers) n.send(to, msg); }
    void invite(Slot m, String p) {
        rsvps.put(p, Rsvp.PENDING);  tell(p, "invited to " + m.title());
        for (Slot s : accepted.getOrDefault(p, List.of()))
            if (s.overlaps(m)) tell(p, "conflict: " + m.title() + " overlaps " + s.title()); }
    void respond(Slot m, String p, Rsvp r) {
        if (!rsvps.containsKey(p))
            throw new IllegalArgumentException(p + " was not invited to " + m.title());
        rsvps.put(p, r);  tell("Asha (organiser)", p + " " + r); } }
public class Main { public static void main(String[] args) {
    Scheduler s = new Scheduler();
    s.notifiers.add((to, msg) -> System.out.println("EMAIL to " + to + ": " + msg));
    s.accepted.put("Priya", List.of(new Slot("Design review", 630, 660)));   // 10:30-11:00
    Slot sprint = new Slot("Sprint planning", 600, 720);                     // 10:00-12:00
    for (String p : List.of("Priya", "Rahul", "Neha")) s.invite(sprint, p);
    s.respond(sprint, "Rahul", Rsvp.ACCEPTED);  s.respond(sprint, "Priya", Rsvp.TENTATIVE);
    System.out.println("RSVPs: " + s.rsvps);
    s.respond(sprint, "Imran", Rsvp.ACCEPTED); } }

Real output:

EMAIL to Priya: invited to Sprint planning
EMAIL to Priya: conflict: Sprint planning overlaps Design review
EMAIL to Rahul: invited to Sprint planning
EMAIL to Neha: invited to Sprint planning
EMAIL to Asha (organiser): Rahul ACCEPTED
EMAIL to Asha (organiser): Priya TENTATIVE
RSVPs: {Priya=TENTATIVE, Rahul=ACCEPTED, Neha=PENDING}
Exception in thread "main" java.lang.IllegalArgumentException: Imran was not invited to Sprint planning
    at Scheduler.respond(Main.java:17)
    at Main.main(Main.java:27)
  • Three invites go out. Priya, who already accepted the design review, also gets conflict: Sprint planning overlaps Design review.
  • The organiser, Asha, is told about each reply. Neha hasn't answered, so she is still PENDING.
  • Imran was never invited, so his reply throws IllegalArgumentException: Imran was not invited to Sprint planning.
  • The notifier is a lambda, (to, msg) -> System.out.println(...): a short way to write a class with one method. Adding phone alerts means adding a second notifier; the Scheduler doesn't change.
  • LinkedHashMap keeps the order in which people were invited; getOrDefault(p, List.of()) returns an empty list for a person with no meetings, instead of null.

9. The class diagram

Room(name, capacity) ── has ──▶ RoomCalendar: TreeMap<start, Interval>   (sorted by start)
Interval [start, end): start < end · overlaps(o) = start < o.end && o.start < end
book(): floorEntry(start) + ceilingEntry(start) → check 2 neighbours, not every meeting
Meeting(title, organiser, room, interval, attendees) · Recurrence(every N days, count)
RoomAllocationStrategy ◁─ FirstFreeRoom · SmallestFitRoom (smallest room that fits)
bookSeries(): check every occurrence first, then book all, or book nothing
Invite: person → Rsvp (PENDING, ACCEPTED, DECLINED, TENTATIVE) · Notifier (Observer) on every change

10. Interview follow-ups

Question Answer
Two people book the same room in the same second? The check and the put must be one step. In one JVM: a lock per room (synchronized on the room, or a ReentrantLock), the same idea as seat locking in episode 75. With a database: an exclusion constraint or a unique slot row per room and time, so the database refuses the second insert.
Time zones? Store every time in UTC (Coordinated Universal Time, the one world clock) and convert to each person's local time only when showing it. Use Instant / ZonedDateTime instead of LocalDateTime.
Find a free slot for five people? Collect everyone's busy intervals, sort by start, merge them, and walk the gaps between them; the first gap at least as long as the meeting wins. The mini project does this.
Cancel one occurrence of a series? Keep the series rule and store an exception date ("not on 18 Nov"); moving one occurrence is an exception plus a one-off meeting.
Edit "this and all following" occurrences? Split the series: end the old rule before that date and start a new rule from it.
Reminders? One more notification event, scheduled for a time before the start (for example 10 minutes).
Room equipment (screen, video)? A set of features on Room; the allocation strategy filters by the features the meeting needs.
Very many rooms? Keep a free-room index per time bucket, or ask each room's TreeMap in parallel; each check is still O(log n).

11. Common mistakes

Mistake What you see (real) Fix
Check only whether the new meeting starts inside a booking Sprint planning 10:00-12:00 booked: true around the 10:30 review a.start < b.end && b.start < a.end
No start < end check Budget call 15:00-14:00 booked: true Throw in the Interval constructor: start 900 must be before end 840
<= instead of < in the overlap rule touching meetings (10-11 and 11-12) refused Half-open intervals: strict <
Scan every booking 10,000 checks per booking TreeMap with floorEntry / ceilingEntry: 2 checks
First free room 4 people -> Hall, 30 people -> no room SmallestFitRoom
Book a series day by day one by one: 4 of 5, a silent hole Check all occurrences first: clashes: [2026-11-18]
Replies as free-form Strings "acepted" stored and never matched enum Rsvp
Accept replies from anyone strangers changing the guest list Imran was not invited to Sprint planning
Mail code inside the scheduler every new channel edits the scheduler Notifier observers

Mini project: a small meeting scheduler

One program that puts it together: rooms with a TreeMap each, a smallest-fit allocation that also checks the room is free at that time, a Meeting with invites and RSVP, conflict warnings, notifications, and a first free slot finder for a group of people.

import java.util.*;

record Interval(int start, int end) {                       // minutes after midnight, [start, end)
    Interval {
        if (start >= end) throw new IllegalArgumentException("start " + start + " must be before end " + end);
    }
    boolean overlaps(Interval o) { return start < o.end && o.start < end; }
    static Interval of(String from, String to) { return new Interval(min(from), min(to)); }
    static int min(String hhmm) { String[] p = hhmm.split(":"); return Integer.parseInt(p[0]) * 60 + Integer.parseInt(p[1]); }
    static String hm(int t) { return String.format("%02d:%02d", t / 60, t % 60); }
    public String toString() { return hm(start) + "-" + hm(end); }
}

enum Rsvp { PENDING, ACCEPTED, DECLINED, TENTATIVE }

interface Notifier { void send(String to, String message); }

class Room {
    final String name; final int capacity;
    private final TreeMap<Integer, Interval> byStart = new TreeMap<>();
    Room(String name, int capacity) { this.name = name; this.capacity = capacity; }
    boolean isFree(Interval iv) {
        var before = byStart.floorEntry(iv.start());
        var after = byStart.ceilingEntry(iv.start());
        return (before == null || !before.getValue().overlaps(iv)) && (after == null || !after.getValue().overlaps(iv));
    }
    void book(Interval iv) {
        if (!isFree(iv)) throw new IllegalStateException(name + " is busy at " + iv);
        byStart.put(iv.start(), iv);
    }
    void release(Interval iv) { byStart.remove(iv.start(), iv); }
}

class Meeting {
    final String title, organiser; final Room room; final Interval time;
    final Map<String, Rsvp> invites = new LinkedHashMap<>();
    Meeting(String title, String organiser, Room room, Interval time) {
        this.title = title; this.organiser = organiser; this.room = room; this.time = time;
    }
    public String toString() { return title + " " + time + " in " + room.name; }
}

interface RoomAllocationStrategy { Optional<Room> pick(List<Room> rooms, int people, Interval time); }

class SmallestFitRoom implements RoomAllocationStrategy {
    public Optional<Room> pick(List<Room> rooms, int people, Interval time) {
        return rooms.stream().filter(r -> r.capacity >= people && r.isFree(time))
                    .min(Comparator.comparingInt(r -> r.capacity));
    }
}

class Scheduler {
    private final List<Room> rooms;
    private final RoomAllocationStrategy strategy;
    private final List<Notifier> notifiers = new ArrayList<>();
    private final Map<String, List<Meeting>> calendarOf = new HashMap<>();   // person -> meetings they accepted
    Scheduler(List<Room> rooms, RoomAllocationStrategy strategy) { this.rooms = rooms; this.strategy = strategy; }
    void subscribe(Notifier n) { notifiers.add(n); }
    private void tell(String to, String msg) { for (Notifier n : notifiers) n.send(to, msg); }

    Meeting schedule(String title, String organiser, Interval time, List<String> people) {
        Room room = strategy.pick(rooms, people.size() + 1, time)
            .orElseThrow(() -> new IllegalStateException("no room for " + (people.size() + 1) + " people at " + time));
        room.book(time);
        Meeting m = new Meeting(title, organiser, room, time);
        accept(m, organiser);
        for (String p : people) invite(m, p);
        return m;
    }
    private void accept(Meeting m, String person) {
        m.invites.put(person, Rsvp.ACCEPTED);
        calendarOf.computeIfAbsent(person, k -> new ArrayList<>()).add(m);
    }
    void invite(Meeting m, String person) {
        m.invites.put(person, Rsvp.PENDING);
        tell(person, "invited to " + m);
        for (Meeting other : calendarOf.getOrDefault(person, List.of()))
            if (other.time.overlaps(m.time)) tell(person, "conflict: " + m.title + " overlaps " + other.title);
    }
    void respond(Meeting m, String person, Rsvp r) {
        if (!m.invites.containsKey(person)) throw new IllegalArgumentException(person + " was not invited to " + m.title);
        if (r == Rsvp.ACCEPTED) accept(m, person); else m.invites.put(person, r);
        tell(m.organiser, person + " " + r + " " + m.title);
    }
    Optional<Interval> firstFreeSlot(List<String> people, int minutes, Interval day) {
        List<Interval> busy = new ArrayList<>();
        for (String p : people) for (Meeting m : calendarOf.getOrDefault(p, List.of())) busy.add(m.time);
        busy.sort(Comparator.comparingInt(Interval::start));
        int t = day.start();
        for (Interval b : busy) {
            if (b.start() - t >= minutes) return Optional.of(new Interval(t, t + minutes));
            t = Math.max(t, b.end());
        }
        return day.end() - t >= minutes ? Optional.of(new Interval(t, t + minutes)) : Optional.empty();
    }
}

public class Main {
    public static void main(String[] args) {
        List<Room> rooms = List.of(new Room("Hall", 40), new Room("Board", 12), new Room("Huddle", 4));
        Scheduler s = new Scheduler(rooms, new SmallestFitRoom());
        s.subscribe((to, msg) -> System.out.println("  [mail to " + to + "] " + msg));

        Meeting review = s.schedule("Design review", "Priya", Interval.of("10:30", "11:00"), List.of("Rahul"));
        System.out.println("Booked: " + review);
        s.respond(review, "Rahul", Rsvp.ACCEPTED);

        Meeting sprint = s.schedule("Sprint planning", "Asha", Interval.of("10:00", "12:00"),
                                    List.of("Priya", "Rahul", "Neha", "Imran", "Vikram"));
        System.out.println("Booked: " + sprint);
        s.respond(sprint, "Neha", Rsvp.DECLINED);
        System.out.println("RSVPs: " + sprint.invites);

        System.out.println("First free hour for Priya and Rahul from 10:00 to 18:00: "
            + s.firstFreeSlot(List.of("Priya", "Rahul"), 60, Interval.of("10:00", "18:00")).orElse(null));
        try {
            s.schedule("All hands", "Asha", Interval.of("10:15", "10:45"), Collections.nCopies(45, "x"));
        } catch (IllegalStateException e) {
            System.out.println("All hands: " + e.getMessage());
        }
    }
}

Real output:

  [mail to Rahul] invited to Design review 10:30-11:00 in Huddle
Booked: Design review 10:30-11:00 in Huddle
  [mail to Priya] Rahul ACCEPTED Design review
  [mail to Priya] invited to Sprint planning 10:00-12:00 in Board
  [mail to Priya] conflict: Sprint planning overlaps Design review
  [mail to Rahul] invited to Sprint planning 10:00-12:00 in Board
  [mail to Rahul] conflict: Sprint planning overlaps Design review
  [mail to Neha] invited to Sprint planning 10:00-12:00 in Board
  [mail to Imran] invited to Sprint planning 10:00-12:00 in Board
  [mail to Vikram] invited to Sprint planning 10:00-12:00 in Board
Booked: Sprint planning 10:00-12:00 in Board
  [mail to Asha] Neha DECLINED Sprint planning
RSVPs: {Asha=ACCEPTED, Priya=PENDING, Rahul=PENDING, Neha=DECLINED, Imran=PENDING, Vikram=PENDING}
First free hour for Priya and Rahul from 10:00 to 18:00: 11:00-12:00
All hands: no room for 46 people at 10:15-10:45

Notes on the design:

  • The organiser counts as a person: the design review needs 2 seats, so it gets the Huddle. Sprint planning needs 6 seats; the Huddle is too small, so it gets the Board room.
  • Rahul accepted the design review, so his sprint-planning invite comes with a conflict warning, as does Priya's (she organised the review, so she accepted it automatically).
  • firstFreeSlot sorts everyone's accepted meetings, walks the gaps, and finds 11:00-12:00 for Priya and Rahul (10:30-11:00 is taken, and 10:00-10:30 is only 30 minutes).
  • 46 people don't fit in any room, so schedule throws: no room for 46 people at 10:15-10:45.
  • Collections.nCopies(45, "x") is a quick list of 45 placeholder names.

Practice

1. The board room has 09:00-10:00 and 11:00-12:00. Which of these can be booked: 08:30-09:00, 09:59-10:01, 10:00-11:00, 11:30-11:45?

Answer

08:30-09:00 yes (touches 09:00), 09:59-10:01 no (overlaps the first by one minute), 10:00-11:00 yes (touches both), 11:30-11:45 no (inside the second).

2. Why does book in section 5 call both floorEntry and ceilingEntry with the start of the new meeting, not its end?

Answer

The floor neighbour is the only earlier meeting that could still be running at our start. The ceiling neighbour is the first meeting starting at or after our start, the only later one that could begin before our end. Using the start for both finds exactly the two meetings around our slot. (Using lowerEntry(end) for the second check also works.)

3. Add a ClosestFloorRoom strategy: rooms have a floor number, and the organiser sits on floor 3. What changes?

Answer

Add int floor to Room and one new class implementing RoomAllocationStrategy: filter rooms with enough capacity, then min(Comparator.comparingInt(r -> Math.abs(r.floor() - 3))). The scheduler keeps calling pick(...); nothing else changes.

4. Make Recurrence support "every Monday, 4 times".

Answer

new Recurrence(7, 4) already does it if the first date is a Monday: every 7 days. A cleaner design stores a frequency enum (DAILY, WEEKLY) and uses plusWeeks(i) for weekly series; for "every Monday and Thursday", store a set of DayOfWeek values and step day by day, keeping the dates whose getDayOfWeek() is in the set.

5. Priya accepts a meeting from 10:00 to 11:00, then is invited to one from 11:00 to 11:30. Does she get a conflict warning?

Answer

No. The intervals only touch: 600 < 690 is true, but 660 < 660 is false, so they don't overlap.

6. Two threads call board.book(...) at the same moment for the same slot. What can go wrong, and how do you fix it?

Answer

Both can read the neighbours before either one puts its interval in, so both see "free" and both book: a race condition (check-then-act). Fix: make book synchronized (one lock per room calendar), so the check and the put happen as one step.

Quick quiz

The board room already has 09:00-10:00 and 11:00-12:00. Intervals are half-open. Which new meeting can be booked? (a) 09:30-10:30 (b) 10:00-11:00 (c) 10:30-11:30 (d) 08:00-12:00

Answer

(b) 10:00-11:00. It only touches both meetings: 10:00 is not before 10:00, and 11:00 is not before 11:00. (a) overlaps the first meeting, (c) the second, and (d) swallows both.

Interview questions

  1. What are the main classes of a meeting room scheduler? Room, Interval, Meeting, plus a calendar per room, an allocation strategy, a recurrence rule, invites with RSVP and notifiers.
  2. How do you check whether two intervals overlap? a.start < b.end && b.start < a.end, with half-open intervals so touching meetings are fine.
  3. Why half-open intervals? So back-to-back meetings (10-11, 11-12) don't count as a clash, and lengths are simply end - start.
  4. How do you check a booking fast? A TreeMap per room keyed by start time; check floorEntry(start) and ceilingEntry(start) only: O(log n).
  5. How do you choose a room? A RoomAllocationStrategy; smallest fit keeps big rooms for big groups.
  6. How do you book a recurring meeting? Expand the occurrences, check them all, then book all or none; store the rule, plus exception dates.
  7. How do you handle invites? An RSVP enum per person, replies only from invited people, conflict warnings from each person's own calendar.
  8. How are people notified? Observers (Notifier) subscribed to the scheduler: mail, phone, chat, reminders, each one a class.
  9. What about concurrency? Make check-and-book one step: a lock per room, or a database constraint across servers.
  10. What about time zones? Store UTC, show local time.

Glossary

Term Meaning, with an example
Meeting room scheduler A system that books rooms for meetings so no room is double-booked
Calendar The list of meetings for a room or a person, in time order
Meeting scheduler requirements What the system must do: book, never double-book, pick a room, repeat, invite, notify
Room A bookable place with a name and a capacity: Room("Board", 12)
Capacity The number of seats in a room: the Hall has 40
Interval A stretch of time with a start and an end: 10:30 to 11:00
Minutes after midnight A simple way to store a time: 10:30 = 630
Meeting A title, an organiser, a room, an interval and attendees
Organiser The person who sets up a meeting: Asha
Attendee A person invited to a meeting: Priya, Rahul, Neha
Double booking Two meetings in the same room at overlapping times
Overlap detection Deciding whether two intervals share time: a.start < b.end && b.start < a.end
Half-open interval [start, end) Includes the start minute, excludes the end minute, so 10-11 and 11-12 just touch
Touching intervals One ends exactly when the other starts; not an overlap
Validation Refusing bad input: start 900 must be before end 840
Record A short Java class for plain data: record Interval(int start, int end)
Compact constructor A record constructor without a parameter list, used for checks: Interval { if (...) throw ...; }
IllegalArgumentException Java's exception for a bad argument
Linear scan Checking every item one by one: 10,000 bookings, 10,000 checks
TreeMap A Java map that keeps its keys sorted; lookups in O(log n)
TreeMap for intervals A TreeMap from start time to interval, so only neighbours need checking
floorEntry(k) The entry with the greatest key ≤ k: the last meeting starting at or before k
ceilingEntry(k) The entry with the smallest key ≥ k: the first meeting starting at or after k
O(log n) Grows like the logarithm of n: about 14 steps for 10,000 items
Big-O notation A way to describe how work grows with input size: O(n), O(log n)
var Lets Java infer a local variable's type: var before = byStart.floorEntry(t)
Room allocation strategy The swappable rule that picks a room: FirstFreeRoom, SmallestFitRoom
Smallest fit Pick the smallest room that still fits everyone
Strategy pattern One interface, one class per rule, chosen at run time (episode 34)
Optional A box that holds a value or is empty: "no room"
Method reference Shorthand for a lambda that calls one method: Room::capacity, free::remove
Comparator An object that decides the order of two values: Comparator.comparingInt(Room::capacity)
Recurring meeting A meeting that repeats on a rule: every day at 9:30, 5 times
Recurrence rule The rule itself: every N days, count times
Occurrence One date of a recurring series: Wednesday 18 Nov
All or nothing (atomic) Either every part happens, or none does: book all 5 stand-ups or none
Exception date One occurrence removed from a series without deleting the series
LocalDateTime A Java date plus time with no time zone: 2026-11-16T09:30
Duration A Java length of time: Duration.ofMinutes(15)
DayOfWeek Java's enum of weekdays: MONDAY
Invite Asking a person to a meeting
RSVP A reply to an invite ("please reply", from French): PENDING, ACCEPTED, DECLINED, TENTATIVE
Tentative "Maybe": not yet sure
enum A Java type with a fixed list of values: enum Rsvp { PENDING, ACCEPTED, DECLINED, TENTATIVE }
Conflict A person invited to two meetings at overlapping times
Notification A message telling someone about a change: an invite, a reply, a conflict
Notifier Our interface for anything that sends notifications
Observer pattern Observers subscribe to a subject and are told about every change (episode 35)
Lambda A short way to write a one-method object: (to, msg) -> System.out.println(msg)
LinkedHashMap A map that remembers insertion order
getOrDefault Map lookup with a fallback value instead of null
Race condition The result depends on which thread runs first: two threads both book one slot
Lock A way to let only one thread at a time run a piece of code
UTC Coordinated Universal Time, one world clock; store times in UTC, show local time
Free slot search Merge everyone's busy intervals and walk the gaps to find a time that suits all

Summary

  • The meeting scheduler requirements give three core classes: Room, Interval and Meeting.
  • "Does it start inside?" missed a meeting that swallows another and let in one that ends before it starts.
  • Overlap detection is one line, a.start < b.end && b.start < a.end, on half-open intervals, and the Interval refuses start >= end.
  • A TreeMap per room with floorEntry and ceilingEntry checks 2 neighbours instead of 10,000 bookings.
  • A room allocation strategy (SmallestFitRoom) puts 4 people in the Huddle and 30 in the Hall.
  • Recurring meetings are booked all or nothing, with the clashing dates reported.
  • Invites and RSVP use an enum, replies only from invited people, conflict warnings, and notifications through observers.
  • Next episode: a digital wallet: wallets, accounts, a ledger with double-entry bookkeeping, idempotency keys and safe concurrent transfers.