Problem
A k
-booking happens when k
events have some non-empty intersection (i.e., there is some time that is common to all k
events.)
You are given some events [start, end)
, after each given event, return an integer k
representing the maximum k
-booking between all the previous events.
Implement the MyCalendarThree
class:
MyCalendarThree()
Initializes the object.int book(int start, int end)
Returns an integerk
representing the largest integer such that there exists ak
-booking in the calendar.
Examples
Example 1:
|
|
Solution
Method 1 - Using TreeMap and Count
To solve this problem, we need to find the maximum number of overlapping intervals (or bookings). The key idea is to use a difference array to track start and end points of intervals and apply an interval sweep technique to calculate the maximum overlap.
We use a TreeMap
(Java) or dict
(Python) to record the times when intervals start (+1
) and end (-1
). This allows us to efficiently count overlapping intervals.
We can use solution similar to My Calendar 2#Method 1 - Using TreeMap and Count.Instead of checking for 2
, we check for k-1
.
Algorithm
- Every time an interval
[start, end)
is added, we update the map by incrementing the start time by1
(indicating an interval starts) and decrementing the end time by-1
(indicating an interval ends). - To calculate the maximum overlap (
k-booking
), traverse through the keys of this map in sorted order and maintain a running sum of active intervals. Update the maximum overlap as the running sum evolves.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
. Thebook
method involves updating the map which takesO(log(n))
due to insertion in a sorted map and a sweep over the keys which takesO(n)
in the worst case.- Hence, the time complexity of
book
isO(n)
per call.
- Hence, the time complexity of
- 🧺 Space complexity:
O(n)
for storing the map, wheren
is the number of unique time points.