Merge Intervals
1 approach, code in every language
Problem description
You are given a collection of intervals where each entry is written as a pair [start, end]. Some of these ranges may touch or overlap one another. Your task is to fuse every group of connected ranges into a single interval so that no two ranges in the result share any common ground.
Return a fresh list containing only the merged, non-overlapping intervals, and the intervals may be returned in any order that the checker accepts (sorted by start is the natural choice).
Example 1
Input: intervals = [[1,4],[3,6],[8,10],[9,12]]
Output: [[1,6],[8,12]]
1-4 and 3-6 touch, so they collapse into 1-6; 8-10 and 9-12 collapse into 8-12.
Example 2
Input: intervals = [[2,3],[3,5]]
Output: [[2,5]]
The two ranges meet exactly at 3, which still counts as overlapping, so they merge.
Constraints
1 ≤ intervals.length ≤ 10^4intervals[i].length == 20 ≤ start ≤ end ≤ 10^4
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Pipeline Sensor Coverage is our own problem on the technique behind Merge Intervals: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free