My Calendar I (LeetCode 729): Solution and Explanation
Build a calendar whose book(startTime, endTime) accepts an event only if it overlaps no event already booked. Events are half-open intervals [start, end), so one event may end at the exact time another begins.
Intuition
The direct approach compares the new event with every booked event. Two half-open intervals [s1, e1) and [s2, e2) overlap exactly when s1 < e2 and s2 < e1. That is O(n) per call.
Booked events never overlap each other, so if you sort them by start time their end times are sorted as well. They sit on the timeline like a row of disjoint blocks.
Drop the new event into that row at the spot its start time belongs. Every event to the left of the spot starts earlier, and the closest one also ends latest among them. Every event to the right starts later, and the closest one starts earliest.
So only the two neighbours matter: the left one must end by startTime and the right one must start no earlier than endTime. If both hold, nothing else can overlap either.
Approach: Sorted events with binary search
- Keep the accepted events sorted by start time (two parallel arrays, or a balanced tree keyed by start).
- For
book(startTime, endTime), binary search fori, the first event whose start is>= startTime. - If
i > 0and eventi - 1ends afterstartTime, return false. - If event
iexists and starts beforeendTime, return false. - Otherwise insert the event at position
iand return true.
Step-by-step example
["MyCalendar","book","book","book"], [[],[10,20],[15,25],[20,30]]
- The calendar starts empty, so
book(10, 20)has no neighbours. Insert it at index 0 and return true. book(15, 25): the first event starting at or after 15 does not exist, soi = 1. The left neighbour[10, 20)ends at 20, which is after 15. Return false.book(20, 30): againi = 1. The left neighbour ends at 20, which is not after 20, so it is clear. There is no right neighbour. Insert at index 1 and return true.- The output is
[null,true,false,true].
Code: Python, Java, C++
1from bisect import bisect_left
2
3class MyCalendar:
4 def __init__(self):
5 self.starts = []
6 self.ends = []
7
8 def book(self, startTime: int, endTime: int) -> bool:
9 i = bisect_left(self.starts, startTime)
10 if i > 0 and self.ends[i - 1] > startTime:
11 return False
12 if i < len(self.starts) and self.starts[i] < endTime:
13 return False
14 self.starts.insert(i, startTime)
15 self.ends.insert(i, endTime)
16 return True1class MyCalendar {
2 private TreeMap<Integer, Integer> cal;
3
4 public MyCalendar() {
5 cal = new TreeMap<>();
6 }
7
8 public boolean book(int startTime, int endTime) {
9 Integer next = cal.ceilingKey(startTime);
10 Integer prev = cal.lowerKey(startTime);
11 if (prev != null && cal.get(prev) > startTime) {
12 return false;
13 }
14 if (next != null && next < endTime) {
15 return false;
16 }
17 cal.put(startTime, endTime);
18 return true;
19 }
20}1class MyCalendar {
2 map<int, int> cal;
3
4public:
5 MyCalendar() {}
6
7 bool book(int startTime, int endTime) {
8 auto next = cal.lower_bound(startTime);
9 if (next != cal.begin() && prev(next)->second > startTime) {
10 return false;
11 }
12 if (next != cal.end() && next->first < endTime) {
13 return false;
14 }
15 cal[startTime] = endTime;
16 return true;
17 }
18};Time and space complexity
O(log n) per call with a balanced tree
The search and the insert are both logarithmic in a TreeMap or std::map. With a sorted array the search is O(log n) but the insert shifts up to n elements, which is still fast for 1000 calls.
O(n)
One entry per accepted event.
Other approaches
Check every booked event (time O(n) per call, space O(n))
Keep a plain list and test the overlap condition s1 < e2 and s2 < e1 against each stored event. Simple and fast enough for the limits here.
Binary search tree of intervals (time O(log n) average, O(n) worst, space O(n))
Insert into a hand-written BST keyed by start. At each node go left if the new event ends by the node's start, right if it starts at or after the node's end, and fail otherwise. Balanced only on average.
Common mistakes
- Treating touching events as overlapping.
[10, 20)and[20, 30)share no moment, so the checks must use strict comparisons: reject only whenend > startTimeorstart < endTime. - Checking only one neighbour. A new event can collide with the event before it (which starts earlier but runs long) or with the event after it.
- Using
floorKey(startTime)in Java for the left neighbour. An event with the same start is a conflict on the right side;lowerKeyplusceilingKeykeeps the two checks clean. - Adding the event before checking. A rejected event must leave the calendar unchanged.
Frequently asked questions
Why is checking two neighbours enough?
Booked events are disjoint and sorted, so every event left of the left neighbour ends even earlier, and every event right of the right neighbour starts even later. If the closest ones are clear, the rest are too.
What if two events have the same start time?
They always overlap, because both contain that start moment. The binary search puts the stored one at index i, and the right-side check catches it since its start is before the new event's end.
How do the follow-up versions differ?
My Calendar II allows double bookings but not triple ones, and My Calendar III asks for the largest number of overlapping events. Both are usually solved with a sweep over start and end counts or a segment tree, because a single sorted list of disjoint events no longer exists.