AAlgoLoopSpaced repetition for LeetCode
MEDIUMIntervalsLeetCode ↗

Merge Intervals

The key idea

Sort the intervals by their start value. Then scan left to right: an interval overlaps the last merged one exactly when its start is less than or equal to that interval's end. If it overlaps, extend the end; otherwise it begins a new block.

Problem

You are given an array intervals where intervals[i] = [start_i, end_i]. Merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Two intervals overlap when one starts before or exactly where the other ends, so [1,4] and [4,5] count as overlapping and merge into [1,5].

Constraints

Examples

Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]]
Input: intervals = [[1,4],[4,5]] Output: [[1,5]]

Complexity

Time: O(n log n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Intervals problems