Scheduling
has come up with the HashMap/TreeMap algorithm to sort the intervals and record the overlaps. The algorithm can be applied to the aforementioned problems with O(nlogn) time complexity.
Here is the idea -
Load all intervals to the
TreeMap, where keys are intervals' start/end boundaries, and values accumulate the changes at that point in time.Traverse the TreeMap (in other words, sweep the timeline). If a new interval starts, increase the counter (
kvalue) by 1, and the counter decreases by 1, if an interval has finished.Calcalulate the number of the active ongoing intervals.
In the following graph, there are 4 intervals/meetings, the k value is the number of rooms or booking sessions.

Problems
My Calendar I (Not the most optimal sol using this approach)
My Calendar II (Not the most optimal sol using this approach)
My Calendar III (Not the most optimal sol using this approach)
thanks for this, such O(n(log(n)) approach using sorted map (TreeMap/RedBlack Tree) also works for car pooling (https://leetcode.com/problems/car-pooling/) but there is a more efficient O(n) solution if number of locations is constrained in range (e.g. from 0 to 1000) : https://leetcode.com/problems/car-pooling/discuss/488622/Java-with-TreeMap-nlog(n)-very-simple
Examples
252. Meeting Rooms
253. Meeting Rooms II
731. My Calendar II
732. My Calendar III
A bit more complicated: 56. Merge Interval
Last updated