My Calendar I

Accept a new event only if it overlaps no booked event, by checking the two booked events next to it.

Write a class MyCalendarI with a method book(start, end) that tries to add an event to a calendar. The event runs from time start up to, but not including, time end, where start is smaller than end. This range is written [start, end).

If the new event overlaps no event already booked, book adds it and returns true. Otherwise it leaves the calendar as it was and returns false. Events that only touch, such as [10, 20) and [20, 30), do not overlap.

Example 1
Input: book(10, 20), book(15, 25), book(20, 30)
Output: true, false, true
Explanation: [15, 25) overlaps [10, 20). [20, 30) starts exactly when [10, 20) ends.
Solution

The Idea

Picture one meeting room and its booking sheet. Someone asks for the room from 10 to 20, the sheet is empty, and the booking goes in. The next person asks for 15 to 25. From 15 to 20 both would need the room, so that request is turned down.

The third request, 20 to 30, is accepted, even though 20 is where the first booking ends. That is what the brackets in [start, end) say: the square bracket includes start, and the round one leaves end out. The first meeting has the room up to time 20 but not at 20, so the next one can begin right then. A range with one end included and the other left out is called a half-open interval.

Look at the picture below. Each row is one call to book, drawn on a time line from 0 to 35, with the booked events in blue above the new event.

Three calls to book on a time line from 0 to 35. book(15, 25) overlaps booked [10, 20) from 15 to 20 and returns false. book(20, 30) only touches [10, 20) at 20 and returns true. book(5, 15), made after [20, 30) is booked, overlaps [10, 20) from 10 to 15 and returns false.

In the top row, the new [15, 25) and the booked [10, 20) share the stretch marked overlap 15 to 20, so book returns false. In the middle row, the new [20, 30) touches at 20 and returns true. The bottom row comes later, once [20, 30) is booked too. The new [5, 15) starts before [10, 20), yet still runs into it from 10 to 15.

So when do two events overlap? When each one starts before the other one ends. [15, 25) starts at 15, before 20, and [10, 20) starts at 10, before 25, so they overlap. [20, 30) starts at 20, which is not before 20, so it fits.

With many bookings, must a new event be checked against every one of them? Look at the bottom row again. Booked events never overlap each other, so in order of their starts they also end in order, left to right along the line.

That leaves only two booked events that can clash with a new one, its two neighbours in order of start. The first is the event that starts at or just before the new start, which clashes if it is still running then. The second is the event that starts at or just after the new start, which clashes if it begins before the new event ends. Any event further left ends even earlier, and any event further right starts even later.

Solution Approach

Turning that idea into code means looking at the simple way and why it is slow, then settling two things: how to keep bookings sorted by start, and how to check a new event's two neighbours.

Comparing with every booking

What is the simplest way to answer book? Keep a list of booked events and test the new one against each of them: two events overlap when each starts before the other ends. That is correct, but every call reads the whole list, so a call made after n bookings takes n steps, and n calls take about n²/2 steps in all.

Keeping bookings sorted by start

How do we reach the two neighbours without reading the whole list? Java's TreeMap, in java.util, is a map that keeps its keys sorted. Here each key is a booked event's start and its value is that event's end. Two booked events never share a start, since they would overlap, so the start works as a key.

A TreeMap can also find the key nearest to a given number from either side. floorEntry(start) returns the entry with the largest key at or below start, and ceilingKey(start) returns the smallest key at or above start. Each returns null when there is no such key.

Checking the two neighbours

Which comparisons decide a booking? The entry from floorEntry(start) is the event before. If its end is greater than start, it is still running when the new event begins, and the booking fails. The key from ceilingKey(start) is the start of the event after. If it is smaller than end, that event begins before the new one is over, and the booking fails too.

Both tests are strict, greater than and smaller than, so events that only touch pass. A booked event with exactly the same start is caught by the first test, because floorEntry includes start itself.

Java Solution

The class works in these steps:

  1. The calendar keeps its bookings in a field, events, a TreeMap from each booked start to its end. It starts empty.
  2. In book, first look up the event before with before = events.floorEntry(start). If before is not null and its end, before.getValue(), is greater than start, return false.
  3. Next, look up the start of the event after with afterStart = events.ceilingKey(start). If afterStart is not null and is smaller than end, return false.
  4. If neither check failed, the new event fits: put start and end into events and return true.

The main method books the three events of Example 1 and then six more that touch, overlap or cover the booked ones, and finally prints the map.

Java
import java.util.Map;
import java.util.TreeMap;

public class MyCalendarI {

    private final TreeMap<Integer, Integer> events = new TreeMap<>();   // start -> end

    public boolean book(int start, int end) {
        Map.Entry<Integer, Integer> before = events.floorEntry(start); // starts at or before start
        if (before != null && before.getValue() > start) {
            return false;                       // still running when the new event starts
        }
        Integer afterStart = events.ceilingKey(start);                 // starts at or after start
        if (afterStart != null && afterStart < end) {
            return false;                       // starts before the new event ends
        }
        events.put(start, end);
        return true;
    }

    static void tryBook(MyCalendarI calendar, int start, int end) {
        System.out.println("book(" + start + ", " + end + ") -> " + calendar.book(start, end));
    }

    public static void main(String[] args) {
        MyCalendarI calendar = new MyCalendarI();
        tryBook(calendar, 10, 20);
        tryBook(calendar, 15, 25);
        tryBook(calendar, 20, 30);
        tryBook(calendar, 5, 15);     // runs into [10, 20)
        tryBook(calendar, 5, 10);     // ends just as [10, 20) starts
        tryBook(calendar, 10, 11);    // same start as [10, 20)
        tryBook(calendar, 25, 28);    // inside [20, 30)
        tryBook(calendar, 0, 40);     // covers everything
        tryBook(calendar, 30, 35);    // starts just as [20, 30) ends
        System.out.println(calendar.events);
    }
}

Running it prints:

Output
book(10, 20) -> true
book(15, 25) -> false
book(20, 30) -> true
book(5, 15) -> false
book(5, 10) -> true
book(10, 11) -> false
book(25, 28) -> false
book(0, 40) -> false
book(30, 35) -> true
{5=10, 10=20, 20=30, 30=35}

The opening three results, true, false, true, match Example 1. Then book(5, 15) -> false is the bottom row of the picture. Nothing starts at or before 5, so the first check has no event to test, and the second check refuses it: afterStart is 10, smaller than 15. On the next line, book(5, 10) -> true, afterStart is 10 again, but 10 is not smaller than the new end, 10, so the event fits just before [10, 20).

book(10, 11) is refused by the first check, since floorEntry(10) finds [10, 20) itself. book(0, 40) covers all three events booked at that point, yet one comparison settles it: afterStart is 5, already before 40. The last line is the map, each start with its end, in order of start and holding only the four accepted events.

Is the second check really needed? A version of book with only the first check, run on book(10, 20) and then book(5, 15), prints book(5, 15) -> true, although both events need the room from 10 to 15.

Complexity

Each call to book does two lookups and at most one insert in the TreeMap, and never reads through all the bookings.

  • Time: O(log n) per call for n bookings, because floorEntry, ceilingKey and put each walk one path down the red-black tree inside TreeMap, a sorted tree kept balanced so that a path has about log n steps.
  • Space: O(n), because the map holds one entry for each of the n accepted bookings, and refused events are never stored.

Ranges kept in a TreeMap by their start also appear in Data Stream as Disjoint Intervals.