Problem
Implement a calendar that allows a range to be booked twice, but rejects a booking that would be triple-booked. Intervals are half-open.
Original: LeetCode 731: My Calendar II.
Examples
Example 1
`MyCalendarTwo: book(10, 20), book(50, 60), book(10, 40), book(5, 15), book(5, 10), book(25, 55)``[true, true, true, false, true, true]`book(5, 15) would triple-book [10, 15).
Constraints
0 <= start < end <= 10^9- At most
1000calls will be made tobook.
Hints
Hint 1
A double booking is allowed. A third interval that intersects an already overlapping pair is not. Endpoints may touch without overlapping.
Hint 2
Track the overlap set explicitly, or maintain a sweep of booking counts and reject a new interval that would push any point to 3.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. On each book, resimulate a sweep of all intervals plus the candidate, and reject if the peak count would reach 3.
Optimal. Two lists: all bookings, and their pairwise overlaps (the double-booked ranges). The candidate is illegal only if it hits a double-booked range.
Alternative. A TreeMap of +1/-1 at start and end, then a prefix walk over the new interval, also works and generalizes to k-bookings.
Complexity
- Time
- O(n)
O(n) time per book if you scan the lists, and O(n) space. A tree of counts is O(n log n) per book and faster for large n.
- Space
- O(n)
Code
class MyCalendarTwo:
def __init__(self) -> None:
self.bookings: list[list[int]] = []
self.doubles: list[list[int]] = []
def book(self, start: int, end: int) -> bool:
if any(start < d[1] and end > d[0] for d in self.doubles):
return False
for b in self.bookings:
if start < b[1] and end > b[0]:
self.doubles.append([max(start, b[0]), min(end, b[1])])
self.bookings.append([start, end])
return True
if __name__ == "__main__":
cal = MyCalendarTwo()
assert cal.book(10, 20) is True
assert cal.book(50, 60) is True
assert cal.book(10, 40) is True
assert cal.book(5, 15) is False
assert cal.book(5, 10) is True
assert cal.book(25, 55) is True
print("ok")import java.util.ArrayList;
import java.util.List;
public class MyCalendarII {
private final List<int[]> bookings = new ArrayList<>();
private final List<int[]> doubles = new ArrayList<>();
boolean book(int start, int end) {
for (int[] d : doubles) {
if (start < d[1] && end > d[0]) return false;
}
for (int[] b : bookings) {
if (start < b[1] && end > b[0]) {
doubles.add(new int[] {Math.max(start, b[0]), Math.min(end, b[1])});
}
}
bookings.add(new int[] {start, end});
return true;
}
public static void main(String[] args) {
var cal = new MyCalendarII();
if (!cal.book(10, 20)) throw new AssertionError();
if (!cal.book(50, 60)) throw new AssertionError();
if (!cal.book(10, 40)) throw new AssertionError();
if (cal.book(5, 15)) throw new AssertionError();
if (!cal.book(5, 10)) throw new AssertionError();
if (!cal.book(25, 55)) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official sample: book(10, 20), book(50, 60) and book(10, 40) succeed; book(5, 15) fails because 10-15 would be booked three times; book(5, 10) and book(25, 55) succeed.
- book(5, 10) only touches 10, so it does not overlap [10, 20).
Follow-ups
- My Calendar III asks for the current maximum k-booking after each insert, which is a sweep or a segment tree.
Interview script
"I remember every booking and also the ranges that are already double-booked. If the new interval hits a double-booked range, I reject it. Otherwise I record its overlaps with existing bookings and then I accept it."
Source: LeetCode 731: My Calendar II
Sources (1)
- LeetCode 731: My Calendar IIleetcode.com