Blind 75 · Intervals

Merge Intervals

Medium

Watch the walkthrough (6:04)

Problem

Given a list of closed intervals in any order, merge every pair that overlaps or touches, and return the result sorted by start.
[1,4] and [4,5] touch, and merge into [1,5].

Examples

Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]

Example 2:
Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]

Example 3:
Input: intervals = [[4,7],[1,4]]
Output: [[1,7]]
Explanation: the input is not sorted; the answer still is.

Example 4:
Input: intervals = [[1,4],[2,3]]
Output: [[1,4]]

Constraints

1 <= intervals.length <= 10^4
intervals[i] is [start, end] with 0 <= start <= end <= 10^5

Prerequisites

Sorting as a setup move — most interval problems are one sort away from a single sweep, and choosing whether to sort by START or by END is the decision that matters.

How to think about it

1. Sort Once, Merge Every Overlap Optimal

Intuition

Sorted by start, every interval that can merge into the last merged interval comes right after it, and once an interval starts after the last one ends, nothing later can reach back. So one sweep after the sort decides everything: if an interval starts at or before the last merged interval's end, the two overlap, and the last interval's end becomes the bigger of the two ends; if not, it is added as the new last interval. These are closed intervals, so touching counts: the check is less than or equal. Take the bigger end, not the incoming one. On the walkthrough's intervals, [3,4] sits inside [2,6]: a merge that took 4 would cut the last interval down to [2,4], [5,7] would then be added on its own, and the answer would be [[2,4],[5,7],[9,13]], which is wrong, because [5,7] overlaps [2,6]. Sort by start; merge an interval into the last if they overlap, or add it.

Algorithm

1. Sort the intervals by start.
2. For each interval, if the merged list has a last interval and this one starts at or before its end, set the last interval's end to the bigger of the two ends.
3. Otherwise add the interval to the merged list.
4. Return the merged list (an array in Java).

Time & Space

Time O(n log n) for the sort; the sweep after it is O(n). Space O(n) for the merged list.

2. Sort by Start, Then Sweep Optimal

Intuition

Sorted by start, an interval can only overlap the one immediately before it in the merged output — so a single sweep decides everything: extend the last merged interval, or begin a new one. Touching counts as overlapping, which is why the comparison is "starts at or before" rather than strictly before.

Algorithm

1. Sort by start.
2. For each interval, if it starts at or before the last merged one's end, raise that end to the larger of the two.
3. Otherwise append it as a new interval.

Time & Space

Time O(n log n), dominated by the sort. Space O(n).