Problem
You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a triple booking.
A triple booking happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.).
The event can be represented as a pair of integers start
and end
that represents a booking on the half-open interval [start, end)
, the range of real numbers x
such that start <= x < end
.
Implement the MyCalendarTwo
class:
MyCalendarTwo()
Initializes the calendar object.boolean book(int start, int end)
Returnstrue
if the event can be added to the calendar successfully without causing a triple booking. Otherwise, returnfalse
and do not add the event to the calendar.
Examples
Example 1:
|
|
Solution
Method 1 - Using TreeMap and Count
Visualize this process as “scanning” from left to right with a “vertical laser”. Each endpoint (either a starting point or an ending point) is treated as an event—where a starting point increments by +1 and an ending point decrements by -1. The cumulative value “count” represents the number of “active” intervals intersected by the vertical laser.
Code
|
|
Dry Run
Lets take input for book as:
|
|
Observe how the map’s ordering shifts during a dry run. This is why we are utilising a TreeMap. Refer: Java TreeMap Class