Scheduling

has come up with the HashMap/TreeMap algorithmarrow-up-right 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 -

  1. Load all intervals to the TreeMap, where keys are intervals' start/end boundaries, and values accumulate the changes at that point in time.

  2. Traverse the TreeMap (in other words, sweep the timeline). If a new interval starts, increase the counter (k value) by 1, and the counter decreases by 1, if an interval has finished.

  3. 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

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