Iteration

Overlapping Intervals

Interval Problems

Given an array of intervals intervals, return whether any of the intervals overlap. You should assume exclusive bounds on the intervals.

Example:

=> returns False\notag \large \texttt{=> returns False}

Example 2:

=> returns True\notag \large \texttt{=> returns True}
First Few Test Cases:

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)O(n \log n). It takes nlognn \log n to sort the intervals, and then nn to iterate.

Space Complexity O(1)O(1)

Mark as Completed:
Submits:
hasOverlap
Test your code to get an output here!
hasOverlap(
)
Test your code to get an output here!