Merge Intervals

Medium Intervals

intervals is a list of intervals, each [start, end] with start ≤ end, in no particular order. An interval holds every point from its start to its end, both ends included.

Two intervals overlap when they share at least one point, even a single end point. Join every group of intervals that overlap, directly or through others in the group, into one interval from the group's smallest start to its largest end.

Return the joined intervals, which no longer overlap, in any order.

Example 1

Input: intervals = [[14,20],[3,5],[16,17],[5,9],[24,24],[9,11]]
Output: [[3,11],[14,20],[24,24]]

[3, 5], [5, 9] and [9, 11] each meet the next at an end point, so the three join into [3, 11]. [16, 17] lies inside [14, 20], which adds nothing, and the single point [24, 24] touches nothing.

Example 2

Input: intervals = [[7,8],[1,3],[4,6]]
Output: [[1,3],[4,6],[7,8]]

Constraints

  • 1 ≤ intervals.length ≤ 10⁵
  • intervals[i] = [start, end]
  • 0 ≤ start ≤ end ≤ 10⁹

Practice this in an AI round

30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.

See the AI round

Watch the explanation

More Intervals

All Intervals problems