Practice · Intervals · 4 of 4

Merge Overlapping Intervals

You are given intervals, a list of ranges [start, end] with start ≤ end. Two ranges overlap if they share at least one point, so [1, 3] and [3, 5] overlap.

Merge every group of overlapping ranges into a single range covering all of them, and return the merged ranges sorted by start.

Example 1

Input
intervals = [[1, 4], [8, 10], [2, 6], [15, 18]]
Output
[[1, 6], [8, 10], [15, 18]]
[1, 4] and [2, 6] overlap, so they become [1, 6].

Example 2

Input
intervals = [[1, 3], [3, 5]]
Output
[[1, 5]]
Sharing the point 3 counts as overlapping.

Constraints

  • intervals holds 1 to 10⁴ ranges.
  • 0 ≤ start ≤ end ≤ 10⁴