Problem Description
Design a calendar system that supports booking events without causing a triple booking. A triple booking occurs when three events overlap at any time point. Each event is represented as an interval [start, end), and an event is allowed if its addition does not make any time point have three or more overlapping events.
Key Insights
- Maintain two separate collections: one for all booked events and one for the periods that are already double booked.
- When booking a new event, first check if it conflicts with any of the double booked intervals. If it does, adding the event would create a triple booking.
- Otherwise, for every existing event, compute and record any new overlap created by the new event with that event. These overlaps form the new double booking intervals.
- Finally, add the new event to the collection of all bookings.
Space and Time Complexity
Time Complexity: O(n) per booking call in the worst case, where n is the number of events booked so far. Space Complexity: O(n) to store all the bookings and overlaps.
Solution
We use a two-list approach:
- A list (or array) to record all booked events.
- A list (or array) to record all intervals where double bookings have occurred.
For each new event:
- First check the new event interval against all intervals in the second list (overlaps). If any overlap exists, then a triple booking would occur, and we return false.
- Otherwise, for each event already booked, if there is an overlap with the new event, compute that overlapping interval and add it to the overlaps list.
- Finally, add the new event to the booked events list and return true.
This approach leverages the idea of interval intersection and simple linear scans over the events. The challenge lies in correctly computing the overlapping intervals and ensuring that triple overlaps are not introduced.