Given an array of intervals intervals
, return whether any of the intervals overlap. You should assume exclusive bounds on the intervals.
Example:
Example 2:
To do this in a single-pass, the idea is to sort the intervals by their starting location. This puts all the intervals in a convenient order, like this:
Now that the intervals are sorted, we can loop through them and check if the current interval overlaps with any other intervals. To do this, you have to check if the current interval overlaps with the previous interval. *
The trick to doing this is to first find the condition when the intervals do not overlap, like this:
The intervals do not overlap if this condition holds:
This means the intervals do overlap if the opposite holds:
Here's the code for checking this:
Time Complexity O(nlogn). It takes nlogn to sort the intervals, and then n to iterate.
Space Complexity O(1)