My Calendar II
Difficulty: Medium · Pattern: Intervals · LeetCode #731
Like My Calendar I, but double bookings are allowed. Only reject an event that would create a triple booking (some moment covered by three events). Intervals are half-open [start, end).
Example
text
book(10,20) → true, book(50,60) → true, book(10,40) → true (double 10–20)
book(5,15) → false (5–15 would triple-book 10–15)
book(5,10) → true, book(25,55) → trueHints
- Keep two lists: all bookings, and the regions that are already double-booked.
- A new event fails exactly when it intersects a double-booked region.
Approach
overlaps: the intersections of pairs of accepted bookings.book(s, e):- If
[s,e)intersects any interval inoverlaps, return false. - Otherwise, for each existing booking that intersects
[s,e), add the intersection[max(s,bs), min(e,be))tooverlaps. - Add
[s,e)to the bookings and return true.
- If
That's O(n) per call. A general sweep-line / difference map alternative adds +1 at start and −1 at end in a sorted map, scans the prefix sums, and rolls back if any count reaches 3. That version generalizes to My Calendar III (max k-booking).
Complexity
Time: O(n) per call. Space: O(n²) worst case for the overlaps (O(n) in practice).
Python solution
class MyCalendarTwo:
def __init__(self):
self.booked, self.overlaps = [], []
def book(self, start, end):
for s, e in self.overlaps:
if start < e and s < end:
return False
for s, e in self.booked:
if start < e and s < end:
self.overlaps.append((max(s, start), min(e, end)))
self.booked.append((start, end))
return TrueJavaScript solution
class MyCalendarTwo {
constructor() { this.booked = []; this.overlaps = []; }
book(start, end) {
for (const [s, e] of this.overlaps) if (start < e && s < end) return false;
for (const [s, e] of this.booked) if (start < e && s < end) this.overlaps.push([Math.max(s, start), Math.min(e, end)]);
this.booked.push([start, end]);
return true;
}
}