Merge Intervals - Problem

Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.

Two intervals overlap if they share at least one common point. For example, [1,3] and [2,6] overlap because they share the range [2,3].

Example: If you have intervals [[1,3],[2,6],[8,10],[15,18]], the first two intervals overlap and should be merged into [1,6], resulting in [[1,6],[8,10],[15,18]].

Input & Output

Example 1 — Basic Overlapping Intervals
$ Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
💡 Note: Intervals [1,3] and [2,6] overlap (share range [2,3]), so merge them into [1,6]. The other intervals [8,10] and [15,18] don't overlap with anything.
Example 2 — All Intervals Merge
$ Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
💡 Note: Intervals [1,4] and [4,5] overlap at point 4, so they merge into [1,5].
Example 3 — No Overlaps
$ Input: intervals = [[1,2],[3,4],[5,6]]
Output: [[1,2],[3,4],[5,6]]
💡 Note: No intervals overlap, so the result is the same as input.

Constraints

  • 1 ≤ intervals.length ≤ 104
  • intervals[i].length == 2
  • 0 ≤ starti ≤ endi ≤ 104

Visualization

Tap to expand
Merge Intervals INPUT Intervals Array: 0 5 10 15 20 [1,3] [2,6] [8,10] [15,18] Overlap! [[1,3],[2,6],[8,10],[15,18]] ALGORITHM STEPS 1 Sort by start Order intervals by start_i 2 Initialize result Add first interval to result 3 Check overlap If curr.start <= last.end 4 Merge or add Update end or add new Merge Example: [1,3] + [2,6] = [1,6] max(3,6) = 6 Time: O(n log n) | Space: O(n) (sorting + linear scan) FINAL RESULT 0 5 10 15 20 [1,6] Merged! [8,10] [15,18] Before vs After Input: 4 intervals Output: 3 intervals Merged: [1,3]+[2,6] --> [1,6] OUTPUT: [[1,6],[8,10],[15,18]] Key Insight: After sorting by start time, overlapping intervals become adjacent. For each interval, if it overlaps with the last merged interval (curr.start <= last.end), extend the end to max(last.end, curr.end). Otherwise, add it as a new non-overlapping interval to the result. TutorialsPoint - Merge Intervals | Optimal Solution (Sort + Linear Scan)
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
78.0K Views
High Frequency
~15 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen