Merge Intervals

Medium#56merge

You get a list of intervals [start, end] in any order. Join every group of intervals that overlap into one interval and return the intervals that are left. Intervals that only touch, like [1, 4] and [4, 5], also count as overlapping. Our example: [9, 12], [1, 4], [5, 7], [4, 5], [10, 11] — the answer is [1, 7], [9, 12].

input
intervals: intervals [start, end] in any order; they may overlap or touch.
returns
The intervals with every overlapping pair merged into one, until no two overlap: they cover the same numbers. Intervals that share only an end, like [1, 3] and [3, 5], overlap too. In any order.
constraints
  • 1 ≤ intervals.length ≤ 1000
  • 0 ≤ startᵢ ≤ endᵢ ≤ 10⁴
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[][]} intervals
 * @return {number[][]}
 */
function merge(intervals) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more intervals problems

Pattern “Intervals” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.