Problem Description
Implement a calendar system that supports adding new events defined by a start and end time. A new event can be booked only if it does not overlap with any existing event in the calendar.
Key Insights
- Use a list (or array) to store currently booked time intervals.
- An event [start, end) does not conflict with another if its end time is less than or equal to the other's start time or its start time is greater than or equal to the other's end time.
- With at most 1000 booking attempts, a simple linear scan for overlapping intervals is acceptable.
- Optionally, for efficiency or scalability, maintain the intervals in a sorted order and use binary search, checking only immediate neighbors for overlaps.
Space and Time Complexity
Time Complexity: O(n) per booking in the worst-case scenario, where n is the number of existing events.
Space Complexity: O(n), as all events are stored.
Solution
The solution maintains a list of tuples (or pairs) representing booked events. When booking a new event, iterate through the list to check if the new interval overlaps with any already booked interval. The overlap condition is evaluated by ensuring that for every booked interval [s, e), the new event [start, end) satisfies (end <= s or start >= e). If it does, append the new event and return true. If there is any overlap, return false without adding the event.