LOW LEVEL DESIGN · MACHINE CODING · MEDIUM · 8 OF 42

Design a Meeting Room Scheduler: Low-Level Design in Java

A meeting room reservation system designed and coded: half-open intervals, a sorted map per room where one lowerEntry lookup detects any conflict, when an interval tree is worth it, room choice as a Strategy, booking and cancelling, listeners for invites, weekly series booked all or nothing, free slot search, a lock per room, and a full Java 17 solution.

Patterns usedStrategyObserver

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 19

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 266 lines, with a small main() demo. Save it as MeetingScheduler.java, then run javac MeetingScheduler.java && java MeetingScheduler.

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Optional;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/** Meeting room booking: sorted calendar per room, room selection strategy, weekly series, listeners. */
public final class MeetingScheduler {

    // ---------- the model ----------
    /** Half-open [start, end): a meeting ending at 11:00 does not clash with one starting at 11:00. */
    record Interval(LocalDateTime start, LocalDateTime end) {
        Interval {
            if (!end.isAfter(start)) throw new IllegalArgumentException("end must be after start");
        }

        boolean overlaps(Interval o) { return start.isBefore(o.end) && o.start.isBefore(end); }
    }

    record Room(String id, int capacity, int floor) {}

    record Booking(String id, String roomId, String organizer, int attendees, Interval when,
                   String seriesId) {}

    record Request(String organizer, int attendees, Interval when, String roomId) {}

    /** One room's calendar: bookings keyed by start time. No two stored bookings overlap. */
    static final class RoomCalendar {
        final Room room;
        private final NavigableMap<LocalDateTime, Booking> byStart = new TreeMap<>();

        RoomCalendar(Room room) { this.room = room; }

        /** The booking with the latest start before our end is the only one that can overlap us. */
        synchronized boolean isFree(Interval w) {
            Map.Entry<LocalDateTime, Booking> e = byStart.lowerEntry(w.end());
            return e == null || !e.getValue().when().end().isAfter(w.start());
        }

        /** Check and insert under one lock, so two callers cannot both win the same slot. */
        synchronized boolean tryReserve(Booking b) {
            if (!isFree(b.when())) return false;
            byStart.put(b.when().start(), b);
            return true;
        }

        synchronized void release(Booking b) { byStart.remove(b.when().start(), b); }

        /** Gaps of at least minLength between the bookings inside a day's opening hours. */
        synchronized List<Interval> freeSlots(Interval day, Duration minLength) {
            List<Interval> out = new ArrayList<>();
            LocalDateTime cursor = day.start();
            for (Booking b : byStart.subMap(day.start(), true, day.end(), false).values()) {
                if (Duration.between(cursor, b.when().start()).compareTo(minLength) >= 0)
                    out.add(new Interval(cursor, b.when().start()));
                if (b.when().end().isAfter(cursor)) cursor = b.when().end();
            }
            if (Duration.between(cursor, day.end()).compareTo(minLength) >= 0)
                out.add(new Interval(cursor, day.end()));
            return out;
        }
    }

    // ---------- strategy and observer ----------
    /** Which rooms to try, in order. */
    interface RoomSelection { List<RoomCalendar> candidates(List<RoomCalendar> rooms, Request r); }

    /** Smallest room that fits, so big rooms stay free for big meetings. */
    static final class BestFit implements RoomSelection {
        public List<RoomCalendar> candidates(List<RoomCalendar> rooms, Request r) {
            return rooms.stream().filter(c -> c.room.capacity() >= r.attendees())
                    .sorted(Comparator.comparingInt((RoomCalendar c) -> c.room.capacity())
                            .thenComparing(c -> c.room.id()))
                    .toList();
        }
    }

    interface BookingListener {
        void onBooked(Booking b);

        void onCancelled(Booking b);
    }

    static final class NoRoomException extends RuntimeException {
        private static final long serialVersionUID = 1L;

        NoRoomException(String msg) { super(msg); }
    }

    // ---------- the scheduler ----------
    private final Map<String, RoomCalendar> rooms = new TreeMap<>();
    private final Map<String, Booking> bookings = new ConcurrentHashMap<>();
    private final List<BookingListener> listeners = new CopyOnWriteArrayList<>();
    private final RoomSelection selection;
    private final AtomicLong seq = new AtomicLong();

    MeetingScheduler(List<Room> roomList, RoomSelection selection) {
        for (Room r : roomList) rooms.put(r.id(), new RoomCalendar(r));
        this.selection = selection;
    }

    void subscribe(BookingListener l) { listeners.add(l); }

    private List<RoomCalendar> candidates(Request r) {
        if (r.roomId() == null) return selection.candidates(List.copyOf(rooms.values()), r);
        RoomCalendar c = rooms.get(r.roomId());
        if (c == null) throw new IllegalArgumentException("unknown room " + r.roomId());
        if (c.room.capacity() < r.attendees()) throw new NoRoomException(r.roomId() + " is too small");
        return List.of(c);
    }

    /** Try candidate rooms in order; the first one whose reserve succeeds wins. */
    Booking book(Request r) {
        String id = "B" + seq.incrementAndGet();
        for (RoomCalendar c : candidates(r)) {
            Booking b = new Booking(id, c.room.id(), r.organizer(), r.attendees(), r.when(), null);
            if (c.tryReserve(b)) {
                bookings.put(b.id(), b);
                listeners.forEach(l -> l.onBooked(b));
                return b;
            }
        }
        throw new NoRoomException("no room for " + r.attendees() + " at " + r.when().start().toLocalTime());
    }

    /** All occurrences in one room, or none: reserve each, and roll back if any slot is taken. */
    List<Booking> bookWeekly(Request first, int weeks) {
        String series = "S" + seq.incrementAndGet();
        for (RoomCalendar c : candidates(first)) {
            List<Booking> made = new ArrayList<>();
            for (int w = 0; w < weeks; w++) {
                Interval at = new Interval(first.when().start().plusWeeks(w),
                        first.when().end().plusWeeks(w));
                Booking b = new Booking(series + "-" + (w + 1), c.room.id(), first.organizer(),
                        first.attendees(), at, series);
                if (!c.tryReserve(b)) break;
                made.add(b);
            }
            if (made.size() == weeks) {
                for (Booking b : made) {
                    bookings.put(b.id(), b);
                    listeners.forEach(l -> l.onBooked(b));
                }
                return made;
            }
            made.forEach(c::release); // roll back and try the next room
        }
        throw new NoRoomException("no single room free for all " + weeks + " weeks");
    }

    boolean cancel(String bookingId) {
        Booking b = bookings.remove(bookingId); // remove first: a booking is cancelled once
        if (b == null) return false;
        rooms.get(b.roomId()).release(b);
        listeners.forEach(l -> l.onCancelled(b));
        return true;
    }

    Optional<Booking> find(String id) { return Optional.ofNullable(bookings.get(id)); }

    List<Interval> freeSlots(String roomId, Interval day, Duration min) {
        return rooms.get(roomId).freeSlots(day, min);
    }

    // ---------- demo ----------
    static final LocalDate DAY = LocalDate.of(2026, 3, 2); // a Monday

    static Interval at(String from, String to) {
        return new Interval(DAY.atTime(LocalTime.parse(from)), DAY.atTime(LocalTime.parse(to)));
    }

    static void check(boolean ok, String what) {
        if (!ok) throw new AssertionError(what);
    }

    static String show(Booking b) {
        return b.id() + " " + b.roomId() + " " + b.when().start().toLocalTime() + "-"
                + b.when().end().toLocalTime();
    }

    public static void main(String[] args) throws InterruptedException {
        MeetingScheduler s = new MeetingScheduler(List.of(
                new Room("Focus-1", 4, 1), new Room("Huddle-2", 6, 2), new Room("Board-3", 12, 3)),
                new BestFit());
        AtomicInteger notices = new AtomicInteger();
        s.subscribe(new BookingListener() {
            public void onBooked(Booking b) { notices.incrementAndGet(); }

            public void onCancelled(Booking b) {
                notices.incrementAndGet();
                System.out.println("  [notify] " + b.attendees() + " people: " + b.id() + " cancelled");
            }
        });

        Booking a = s.book(new Request("product-manager", 3, at("10:00", "11:00"), null));
        Booking b = s.book(new Request("tech-lead", 4, at("10:30", "11:30"), null));
        Booking c = s.book(new Request("designer", 4, at("11:00", "12:00"), null));
        Booking d = s.book(new Request("director", 10, at("10:00", "11:00"), null));
        for (Booking x : List.of(a, b, c, d)) System.out.println(show(x));
        check(a.roomId().equals("Focus-1") && b.roomId().equals("Huddle-2"), "best fit, then next room");
        check(c.roomId().equals("Focus-1"), "11:00 start touches an 11:00 end: no clash");
        try {
            s.book(new Request("recruiter", 10, at("10:15", "10:45"), null));
            throw new AssertionError("should be full");
        } catch (NoRoomException e) {
            System.out.println("10 people at 10:15: " + e.getMessage());
        }
        check(s.cancel(d.id()) && !s.cancel(d.id()), "cancel once");
        Booking e = s.book(new Request("recruiter", 10, at("10:15", "10:45"), null));
        System.out.println("after cancel: " + show(e));

        // A weekly series must sit in one room; week 3 of Huddle-2 is taken, so it moves to Board-3.
        LocalDateTime week3 = DAY.plusWeeks(2).atTime(9, 0);
        s.book(new Request("qa-lead", 5, new Interval(week3, week3.plusMinutes(30)), "Huddle-2"));
        List<Booking> standup = s.bookWeekly(new Request("scrum-master", 5, at("09:00", "09:30"), null), 4);
        System.out.println("weekly standup x" + standup.size() + " in " + standup.get(0).roomId()
                + ", series " + standup.get(0).seriesId());
        check(standup.stream().allMatch(x -> x.roomId().equals("Board-3")), "series in one room");
        check(s.freeSlots("Huddle-2", at("09:00", "09:30"), Duration.ofMinutes(15)).size() == 1,
                "rolled back Huddle-2");

        List<String> gaps = s.freeSlots("Focus-1", at("09:00", "13:00"), Duration.ofMinutes(30)).stream()
                .map(i -> i.start().toLocalTime() + "-" + i.end().toLocalTime()).toList();
        System.out.println("Focus-1 free (30+ min, 09-13): " + gaps);
        check(gaps.equals(List.of("09:00-10:00", "12:00-13:00")), "free slots");

        // Ten people race for the same room and slot: exactly one booking wins.
        ExecutorService pool = Executors.newFixedThreadPool(10);
        CountDownLatch go = new CountDownLatch(1);
        AtomicInteger won = new AtomicInteger();
        for (int i = 0; i < 10; i++) {
            pool.submit(() -> {
                try {
                    go.await();
                    s.book(new Request("engineer", 2, at("15:00", "16:00"), "Focus-1"));
                    won.incrementAndGet();
                } catch (NoRoomException ignored) {
                    // lost the race
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        go.countDown();
        pool.shutdown();
        check(pool.awaitTermination(5, TimeUnit.SECONDS), "pool finished");
        System.out.println("race for Focus-1 15:00: 10 tries, " + won.get() + " booked");
        check(won.get() == 1, "no double booking");
        System.out.println("notifications sent: " + notices.get());
        System.out.println("all checks passed");
    }
}

Notes

Requirements

Fix the scope. Rooms have an id, a capacity and a floor. A booking request names the organizer, the number of people, a start and an end, and either asks for a specific room or lets the system pick one that fits. Bookings in the same room never overlap. People can cancel, set up weekly meetings, and see a room's free slots. Attendees get notified. Many people book at the same time.

Clarify the rules that change the code. Can one meeting end at eleven and the next start at eleven in the same room? Yes, so intervals are half-open: the end is not included. If several rooms fit, which one? The smallest, so big rooms stay free. If one week of a weekly series is taken, do we split rooms? No, the whole series goes in one room or fails. And a single occurrence can be cancelled by its id.

Requirements
  • rooms: id, capacity, floor
  • book(who, people, start, end)
  • any room that fits, or a
  • specific room
  • never two bookings overlapping
  • in one room
  • cancel(bookingId)
  • weekly meetings
  • notify attendees
  • free slots in a room today
  • many people booking at once
Clarify first
  • 10-11 then 11-12, same room?
  • allowed: end is exclusive
  • which room if many fit?
  • the smallest that fits
  • weekly, one week is taken?
  • same room for all, or fail
  • cancel one of a series?
  • yes, by booking id
  • time zones? one, local time

Entities

The entities. A room is plain data. A booking ties an organizer and a head count to a room and an interval. A request is what the caller asks for before a room is chosen. The key design choice is a calendar per room, which holds that room's bookings and owns the conflict check. The scheduler is the service object on top: it picks rooms, keeps an index of bookings by id, and tells listeners.

Class diagram

Turn them into records. The interval validates that the end is after the start, and owns the overlap rule: two half-open intervals overlap when each one starts before the other ends. With that rule, ten to eleven and eleven to twelve do not overlap, which is what people expect. Room, booking and request are records too, so they are immutable and safe to pass between threads. Only the calendars change.

Value types
record Interval(LocalDateTime start,
                LocalDateTime end) {
  boolean overlaps(Interval o) {
    return start.isBefore(o.end)
        && o.start.isBefore(end);
  }
}
record Room(id, capacity, floor)
record Booking(id, roomId, organizer,
    attendees, when, seriesId)
record Request(organizer, n, when, room)

Conflict detection

Conflict detection. Keep each room's bookings in a tree map sorted by start time. Because stored bookings never overlap each other, only one can clash with a new slot: the one with the latest start before our end. Tree map's lower entry finds it in log time. If it ends after our start, we clash; otherwise the slot is free. Compare that with scanning every booking in the room, which is linear and is the answer interviewers hope you improve on.

isFree(w) in O(log n)
TreeMap<LocalDateTime, Booking> byStart

e = byStart.lowerEntry(w.end)
free = e == null
    || !e.end.isAfter(w.start)

room has 10-11 and 11-12
ask 10:30-11:30:
  lowerEntry(11:30) is 11-12
  11-12 ends after 10:30: clash

Sorted map or tree?

When do you need an interval tree? Only when the stored intervals can overlap each other, like one person's calendar with clashing invites, or one index across every room, and you ask for all intervals that touch a time. An interval tree keeps the maximum end in each subtree and answers in log n plus the number of matches. Inside one room nothing overlaps, so a sorted map is simpler and just as fast. Say that trade-off out loud.

Which structure
  • list + scan: O(n), fine for
  • a demo, say why it is slow
  • sorted map per room: O(log n)
  • works when stored intervals
  • never overlap each other
  • interval tree: O(log n + k)
  • when stored ones DO overlap,
  • e.g. a person's calendar or
  • all rooms in one index

Strategy: room choice

Which room should a meeting of three get? That is a policy, so it is a Strategy. The interface returns candidate rooms in the order to try. Our default, best fit, keeps rooms with enough seats and sorts by capacity, so a three-person meeting takes a four-seat room and leaves the twelve-seat boardroom free. Nearest to the organizer's floor, or rooms with video equipment, are new classes, and the scheduler does not change.

RoomSelection
interface RoomSelection {
  List<RoomCalendar> candidates(
      List<RoomCalendar> all, Request r);
}
BestFit: capacity >= people,
  smallest first, then by id

NearestFloor, HasVideo, Quietest:
  new classes, scheduler unchanged

Flow: book

Walk a booking. A tech lead wants four people from ten thirty. The strategy offers Focus-1 first, but it has a meeting until eleven, so its reserve fails. Huddle-2 is free, its reserve succeeds, and the booking is stored in an index by id and announced to listeners. If every candidate fails, throw a clear no-room error that says what was asked. A specific room request just narrows the candidates to that one room.

book(request)
id = next id
for (c : candidates(request)) {
  b = new Booking(id, c.room, ...)
  if (c.tryReserve(b)) {
    byId.put(id, b)
    notify listeners; return b
  }
}
throw: no room for 4 at 10:30

Flow: cancel

Cancelling removes the booking from the id index first. That removal is atomic on a concurrent map, so if two people press cancel together, only one finds it, and the other gets false. Then the room's calendar releases the slot, and listeners hear about the cancellation so attendees get a notice. In the demo the freed boardroom slot is booked again straight away.

cancel(id)
b = byId.remove(id)
if (b == null) return false
calendar(b.room).release(b)
listeners: onCancelled(b)
return true

second cancel(B4): false

Observer: notifications

Notifications use the Observer pattern. The scheduler knows one interface with two methods, booked and cancelled. Email invites, calendar sync, a reminder service and the screens outside each room all subscribe. The scheduler never knows how many there are or how they send things. In a real service these calls would go onto a queue so a slow mail server never holds up a booking.

BookingListener
interface BookingListener {
  void onBooked(Booking b);
  void onCancelled(Booking b);
}
listeners = CopyOnWriteArrayList

email invites, calendar sync,
reminders 10 min before,
room display panels

Recurring meetings

Weekly meetings expand into one booking per week, all in the same room. For each candidate room, reserve the occurrences one by one. If any week is already taken, release the ones we made and move to the next room. In the demo, week three of Huddle-2 is taken, so the standup is rolled back there and lands in the boardroom for all four weeks. All or nothing per room is the rule we agreed while clarifying.

bookWeekly(first, weeks)
for (c : candidates) {
  made = []
  for (w in 0..weeks-1)
    if (!c.tryReserve(occurrence w))
      break
    made.add(it)
  if all made: notify, return made
  made.forEach(c::release) // undo
}
throw: no room free every week

Free slots

Finding free slots is one walk over the sorted map. Take the bookings inside the day's opening hours in start order, and move a cursor forward: whenever the next booking starts at least the minimum length after the cursor, that gap is free. Then the cursor jumps to the booking's end. After the last booking, the rest of the day may be free too. For Focus-1 between nine and one, that gives nine to ten and twelve to one.

freeSlots(day, minLength)
cursor = day.start
for (b : byStart.subMap(day))
  if (b.start - cursor >= min)
    add [cursor, b.start)
  cursor = max(cursor, b.end)
if (day.end - cursor >= min)
  add [cursor, day.end)

Focus-1, 09-13, 30 min or more:
  09:00-10:00, 12:00-13:00

Concurrency

Concurrency. If checking and inserting were separate steps, two people could both see the slot free and both insert. So try reserve does the check and the insert inside one synchronized method on that room's calendar. Each room has its own lock, so bookings for different rooms never wait for each other. In the demo ten threads race for the same room and hour, and exactly one wins, every run.

No double booking
  • tryReserve = isFree + put,
  • one synchronized method
  • lock per room: rooms never
  • wait on each other
  • byId: ConcurrentHashMap
  • listeners: CopyOnWriteArrayList
  • records: immutable
  • test: 10 threads, one slot
  • exactly 1 booked

Extensibility

Extensions. Monthly or custom repeats become a recurrence rule strategy that produces the dates. Boardroom bookings that need approval get a pending state. Holding a slot while someone fills in the form is a hold that expires after a few minutes. Cleaning time between meetings is a padded interval. Several offices are a map of schedulers by site. None of these touch the conflict check.

Extension points
  • monthly or custom repeats:
  • a RecurrenceRule strategy
  • approval for big rooms:
  • booking state PENDING
  • hold a slot while choosing:
  • a hold that expires
  • buffer between meetings:
  • pad the interval by 5 min
  • many offices: a map per site

Testing

The full code is below the player. The demo books four meetings and checks best fit, the move to the next room, and that eleven o'clock back to back is allowed. A ten-person meeting at ten fifteen finds no room until the boardroom booking is cancelled. A weekly standup rolls back from Huddle-2 and lands in the boardroom. Then free slots, and ten threads racing for one slot.

Run it
B1 Focus-1 10:00-11:00
B2 Huddle-2 10:30-11:30
B3 Focus-1 11:00-12:00
B4 Board-3 10:00-11:00
10 people at 10:15: no room for 10 at 10:15
after cancel: B6 Board-3 10:15-10:45
weekly standup x4 in Board-3, series S8
Focus-1 free (30+ min, 09-13):
  [09:00-10:00, 12:00-13:00]
race for Focus-1 15:00: 10 tries, 1 booked
all checks passed

Follow-ups

Expect follow-ups. The minimum number of rooms for a list of meetings: sort by start and keep a min-heap of end times, reusing a room when the earliest end is before the next start; the heap's largest size is the answer. Stopping a person from being in two meetings means a calendar per person too. With a database, an exclusion or unique constraint makes the store itself reject overlaps.

Follow-ups to expect
  • fewest rooms for a day's
  • meetings? sort starts, keep
  • a min-heap of end times
  • person double-booked?
  • a calendar per person too
  • thousands of rooms?
  • index by capacity and floor
  • persist? unique constraint or
  • exclusion constraint in SQL

Say it like this

The short version. Intervals are half-open. Each room keeps its bookings in a tree map by start time, and lower entry of our end finds the only booking that could clash, in log time. Room choice is a strategy, notifications are observers, and a weekly series is reserved all or nothing in one room. Reserving is a check and insert inside one lock per room, so two people never get the same slot.

In the interview
  • "Intervals are half-open. Each
  • room has a TreeMap by start;
  • lowerEntry(end) finds the only
  • booking that can clash, in
  • log n. Room choice is a
  • strategy, notices are
  • observers, series are all or
  • nothing, and reserve is
  • synchronized per room."

Interview questions

How do you detect a booking conflict efficiently?

Keep each room's bookings in a TreeMap keyed by start time. Since stored bookings never overlap, only the booking with the greatest start before the new end can clash; lowerEntry(end) finds it in O(log n), and there is a conflict if it ends after the new start.

Why use half-open intervals?

With [start, end) a meeting ending at 11:00 and one starting at 11:00 do not overlap, which matches how people book. The overlap test is simply a.start before b.end and b.start before a.end, with no special cases at the edges.

When would you use an interval tree instead of a sorted map?

When the stored intervals can overlap each other, such as one person's calendar or a single index over all rooms, and you need every interval touching a time. An interval tree answers in O(log n + k). Within one room bookings never overlap, so a sorted map is enough.

How do you prevent two people from booking the same room at the same time?

Make check and insert one atomic step: tryReserve is synchronized on that room's calendar, so only one caller can see the slot free and insert. Locks are per room, so different rooms never contend.

How do you choose which room to give?

A RoomSelection strategy returns candidate rooms in order. Best fit filters by capacity and sorts smallest first, keeping big rooms free; other strategies like nearest floor or rooms with video are new classes.

How do you book a weekly meeting?

Expand it into one booking per week and try to reserve all of them in one candidate room. If any week is taken, release those already reserved and try the next room. Only when every week succeeds are the bookings stored and announced.

What is the minimum number of rooms needed for a set of meetings?

Sort meetings by start time and keep a min-heap of end times of rooms in use. For each meeting, if the earliest end is at or before its start, reuse that room by popping it; push the new end. The largest heap size seen is the answer, in O(n log n).

How would you find free slots in a room?

Walk that day's bookings in start order with a cursor at the opening time; each gap between the cursor and the next start of at least the minimum length is free, then move the cursor to the booking's end. Finally check the gap to closing time.