We are given a list of intervals, and some of them may overlap. The goal is to merge all overlapping intervals and return a new list where no intervals overlap, while still covering exactly the same ranges.
The key idea is: after sorting the intervals by their start time, we only ever need
to compare the current interval — the interval we are currently processing — with the
last interval inserted into the result — the most
recent interval already added to our merged output.
If they overlap, we merge them by expanding that last interval’s end; otherwise, we
start a new interval in the result.
This works for both chains of overlaps (A overlaps B, B overlaps C) and
shared overlaps (A overlaps both B and C even if B and C don’t overlap each other),
when the intervals are in start-time order A → B → C.
Because we keep the merged range updated as we go, a single left-to-right pass
is enough to merge all overlapping intervals.
High-Level Strategy
-
Step 1: Sort the intervals by start time.
We first sort all intervals in ascending order of their start value. After sorting, any intervals that overlap will appear next to each other. This makes it possible to merge them in a single linear sweep. -
Step 2: Build the merged result from left to right.
We create an array calledfinalIntervalsand put the first interval into it. That interval becomes the last inserted interval — the one we compare against as we process the rest.
As we move through the remaining intervals one by one, each becomes the current interval for comparison:-
If the current interval overlaps with the last inserted interval:
Two intervals overlap if the current interval’s start is less than or equal to the last inserted interval’s end. In that case, we merge them by extending the end of the last inserted interval to cover both ranges.
We only update the end of the last inserted interval. We do not need to change its start, because the list is already sorted by start time. This ensures that the current interval never starts before the last inserted interval. -
If the current interval does not overlap:
That means it starts strictly after the last inserted interval ends. In that case, we cannot merge them. We simply append the current interval as a new block intofinalIntervals, and it becomes the new last inserted interval.
-
If the current interval overlaps with the last inserted interval:
-
Step 3: Return the result.
After we’ve scanned all intervals,finalIntervalsholds the merged, non-overlapping intervals in sorted order.
Why This Works
-
Sorted input enables local merging:
Once intervals are sorted by their start time, any possible overlap can only occur with the most recently inserted interval in the result. Earlier intervals are guaranteed to end before the current one starts, so there’s no need to look back further. -
Output correctness:
ThefinalIntervalslist remains sorted and non-overlapping because all overlapping ranges are merged as they are processed.