Calendar 2
Design a calendar system that allows you to book events. A double booking is allowed, but a triple booking is strictly prohibited.
A double booking happens when two events intersect. A triple booking happens when three events share a common moment in time. The event can be represented as a half-open interval [start, end), meaning it starts at start and ends right before end.
Implement the MyCalendarTwo class:
- MyCalendarTwo(): Initializes the calendar object.
- boolean book(int start, int end): Returns true if the event can be added to the calendar successfully without causing a triple booking. Otherwise, returns false and does not add the event to the calendar.
Example 1:
Input: ["MyCalendarTwo", "book", "book", "book", "book"]
[[], [10, 20], [15, 25], [18, 22], [20, 30]]
Output: [null, true, true, false, true]
Explanation: The first two bookings [10, 20) and [15, 25) are successful, creating a permitted double booking between time 15 and 20. The third request [18, 22) attempts to book a time that overlaps with both existing events specifically between 18 and 20. This would cause an illegal triple booking, so it is rejected and returns false. Finally, the fourth request [20, 30) is approved because it starts exactly as the first event ends, meaning it only overlaps with the second event, safely remaining within the double booking limit.
Example 2:
Input: ["MyCalendarTwo", "book", "book", "book", "book"]
[[], [20, 50], [10, 60], [30, 40], [50, 70]]
Output: [null, true, true, false, true]
Explanation: We first book a large block [20, 50), followed by an even larger block [10, 60) that completely envelopes the first one. This successfully establishes a massive double-booked region extending from time 20 to 50. The third request [30, 40) falls directly into the middle of this existing double-booked zone and is instantly rejected to prevent a triple booking. The final booking [50, 70) succeeds because it only overlaps with the tail end of the [10, 60) event, as the first event ends exactly at 50.
Now Your Turn!
Pick the correct output for the given inputInput: ["MyCalendarTwo", "book", "book", "book", "book", "book"]
[[], [5, 15], [10, 20], [25, 35], [30, 40], [12, 32]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 0 <= start < end <= 109
- At most 1000 calls will be made to book.