Throw the endpoints of the intervals into the array, labeling them as start or end points. Sort them by breaking the tacks, placing the end points in front of the starting points if the intervals are closed, or vice versa if they are half open.
1S, 2S, 3E, 4E, 5S, 10E, 12S, 13S, 14E, 15E
Then iterate over the list, tracking how many intervals we are in (this corresponds to the number of processed start points minus the number of end points). Whenever we press the starting point while we are already in the interval, this means that we must have overlapping intervals.
1S, 2S, 3E, 4E, 5S, 10E, 12S, 13S, 14E, 15E ^ ^ overlap overlap
We can find which intervals overlap with them, storing data along with the endpoints and keeping track of which gaps we are in.
This solution is O (N logN), and the main factor is sorting.
marcog Dec 28 2018-10-12T00: 00Z
source share