Merge Intervals

MediumIntervals

You get a list of intervals, each [start, end], in no particular order. Merge every group of overlapping intervals into one interval that covers them all, and return the intervals that are left.

Two intervals that only touch, like [5, 7] and [7, 9], overlap. The answer’s intervals can come back in any order.

Examples

Example 1
Input:  intervals = [[7, 12], [1, 4], [8, 9], [3, 5]]
Output: [[1, 5], [7, 12]]

[1, 4] and [3, 5] overlap, and [8, 9] lies wholly inside [7, 12].

Example 2
Input:  intervals = [[5, 7], [7, 9]]
Output: [[5, 9]]

They touch at 7, which counts as overlapping.

Constraints

  • 1 ≤ intervals.length ≤ 10⁴
  • 0 ≤ start ≤ end ≤ 10⁴

Stuck?

Hint 1

Sort the intervals by start. Then each one either overlaps the last interval you kept, or begins a new one.

Hint 2

When it overlaps, stretch the last kept interval’s end to the larger of the two ends, not simply to the new interval’s end: it may sit entirely inside.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 9 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur