Calender 2
Approach 2: Line Sweep
Intuition
The previous approach works well for the given problem, where we need to avoid triple bookings. However, if the requirements change such as checking for four overlapping bookings, the method becomes less flexible. We'd need to introduce additional lists, for example, to track triple bookings, making the solution harder to maintain and extend.
To address this, we can use a more flexible and standard solution: the Line Sweep algorithm. This approach is common for interval-related problems and can easily handle changes, such as checking for four or more overlapping bookings.
The Line Sweep algorithm works by marking when bookings start and end. For each booking (start, end)
, we mark the start
point by increasing its count by 1
(indicating a booking begins), and we mark the end
point by decreasing its count by 1
(indicating a booking ends). These marks are stored in a map, which
keeps track of the number of bookings starting or ending at each point.
Once all bookings are processed, we compute the prefix sum over the
map. The prefix sum at any point tells us how many active bookings
overlap at that moment. If the sum at any point exceeds 2
, it means we have a triple booking. At this point, the function should return false
to prevent adding a new booking. If no triple booking is found, the function returns true
, and the booking is allowed.
This approach is easily extendible. If we wanted to check for four or
more bookings instead of three, we would simply adjust the threshold
from 2
to 3
when calculating the prefix sum.
This flexibility makes the Line Sweep method a more robust solution for
variations of the problem.
Algorithm
-
Class
MyCalendarTwo
will have two data members,maxOverlappedBooking
which is the maximum number of concurrent bookings possible at a time, andbookingCount
which is a map from integer to integer with the time point as the key and number of bookings as the value. -
Initialize
maxOverlappedBooking
as2
, as we need to check for triple booking. -
Define the function
book(start, end)
as:- Increase the number of bookings for the time
start
and decrease the number of bookings forend
by1
in the mapbookingCount
. - Iterate over each key-value pair in the map in ascending order of
keys to find the prefix sum. Add the value in the map to the count
overlappedBooking
. - If
overlappedBooking
is more than two, it implies that this is triple booking. Hence, we should return false. Also, we need to revert the changes in the map as this booking shouldn't be added. - If we reach here, it implies no triple booking and hence returns
true
.
- Increase the number of bookings for the time
Comments
Post a Comment