My Calendar II (LeetCode 731): Solution and Explanation
Build a calendar whose book(startTime, endTime) accepts an event unless it would make some moment hold three events. Two events may share time; three may not. Events are half-open intervals [start, end).
Intuition
A moment becomes triple booked only if it is already covered by two events and the new event covers it too. So the question is not about single events at all, it is about the regions that are already double booked.
If you keep a list of those double-booked regions, the check is one scan: does the new event meet any of them? If yes, it must be rejected.
When the event is accepted, the set of double-booked regions grows. Every stored event that meets the new one shares exactly the piece [max(s1, s2), min(e1, e2)) with it, and that piece is now covered twice.
Recording those pieces keeps the second list correct for the next call, and the first list of all events is what you intersect against.
Approach: Booked list plus overlap list
- Keep
booked, every accepted event, andoverlaps, every region covered by two events. - For
book(startTime, endTime), scanoverlaps. If any region satisfiess < endTime and startTime < e, return false. - Otherwise scan
booked. For each event that meets the new one, append[max(s, startTime), min(e, endTime))tooverlaps. - Append the new event to
bookedand return true.
Step-by-step example
["MyCalendarTwo","book","book","book","book","book","book"], [[],[10,20],[50,60],[10,40],[5,15],[5,10],[25,55]]
book(10, 20)andbook(50, 60): there are no double-booked regions and they do not meet each other, so both are accepted.book(10, 40): no double-booked region yet. It meets[10, 20), so[10, 20)becomes double booked. Return true.book(5, 15): it meets the double-booked region[10, 20), so[10, 15)would hold three events. Return false and store nothing.book(5, 10): it ends at 10, so it only touches[10, 20)and meets no stored event. Return true.book(25, 55): it misses[10, 20). It meets[10, 40)and[50, 60), adding[25, 40)and[50, 55)to the overlaps. Return true. The output is[null,true,true,true,false,true,true].
Code: Python, Java, C++
1class MyCalendarTwo:
2 def __init__(self):
3 self.booked = []
4 self.overlaps = []
5
6 def book(self, startTime: int, endTime: int) -> bool:
7 for s, e in self.overlaps:
8 if s < endTime and startTime < e:
9 return False
10 for s, e in self.booked:
11 if s < endTime and startTime < e:
12 self.overlaps.append((max(s, startTime), min(e, endTime)))
13 self.booked.append((startTime, endTime))
14 return True1class MyCalendarTwo {
2 private List<int[]> booked;
3 private List<int[]> overlaps;
4
5 public MyCalendarTwo() {
6 booked = new ArrayList<>();
7 overlaps = new ArrayList<>();
8 }
9
10 public boolean book(int startTime, int endTime) {
11 for (int[] o : overlaps) {
12 if (o[0] < endTime && startTime < o[1]) {
13 return false;
14 }
15 }
16 for (int[] b : booked) {
17 if (b[0] < endTime && startTime < b[1]) {
18 overlaps.add(new int[]{Math.max(b[0], startTime), Math.min(b[1], endTime)});
19 }
20 }
21 booked.add(new int[]{startTime, endTime});
22 return true;
23 }
24}1class MyCalendarTwo {
2 vector<pair<int, int>> booked, overlaps;
3
4public:
5 MyCalendarTwo() {}
6
7 bool book(int startTime, int endTime) {
8 for (auto& o : overlaps) {
9 if (o.first < endTime && startTime < o.second) {
10 return false;
11 }
12 }
13 for (auto& b : booked) {
14 if (b.first < endTime && startTime < b.second) {
15 overlaps.push_back({max(b.first, startTime), min(b.second, endTime)});
16 }
17 }
18 booked.push_back({startTime, endTime});
19 return true;
20 }
21};Time and space complexity
O(n) per call
Each call scans the overlap list and the booked list once. Over n calls that is O(n^2), about a million steps for 1000 calls.
O(n)
The booked list holds n events. Since no moment is ever covered three times, the double-booked regions are disjoint and number at most about n.
Other approaches
Sweep line over a sorted map (time O(n) per call, space O(n))
Add +1 at startTime and -1 at endTime in a sorted map, then walk the map keeping a running count. If the count ever reaches 3, undo the two updates and return false.
Segment tree with lazy propagation (time O(log C) per call, space O(n log C))
A dynamic segment tree over the time range that supports range add and range max. Book by querying the max on the range, rejecting if it is 2, otherwise adding 1. Worth it only when calls are far more numerous.
Common mistakes
- Checking against
bookedbeforeoverlapsand recording overlaps that you later throw away. A rejected event must leave both lists unchanged, so testoverlapsfirst. - Treating touching events as overlapping.
[5, 10)and[10, 20)share no moment, so the test must be strict:s < endTime and startTime < e. - Storing the whole stored event in
overlapsinstead of only the shared piece. Only the intersection is covered twice. - Assuming the booked events are disjoint as in My Calendar I. Here they can overlap, so there is no single sorted chain to binary search.
Frequently asked questions
Why is it enough to compare against the double-booked regions?
A triple booking needs a moment covered by two stored events plus the new one. The moments covered by two stored events are exactly the regions in the overlap list, so meeting one of them is both necessary and sufficient.
Can the overlap list hold overlapping regions?
No. If two regions in it overlapped, some moment would be covered by three events, which the calendar never allows. So the regions are disjoint.
How does this relate to My Calendar III?
My Calendar III asks for the largest number of events covering one moment after each booking. The sweep line over +1 and -1 counts answers that directly, which is why it is the usual pattern for the whole series.