☰ All problems

60. Merge Intervals

MediumArraySortingIntervals

You are given an array of closed intervals intervals, where intervals[i] = [start, end] and start <= end. The input is not necessarily sorted.

Merge every group of overlapping intervals into one interval and return the result. Intervals that merely touch, such as [1,2] and [2,3], also count as overlapping.

Return the merged intervals sorted by start (the answer is then unique).

Example 1
Input: intervals = [[1,4],[2,5],[7,9]]
Output: [[1,5],[7,9]]

Explanation: [1,4] and [2,5] overlap on [2,4], so they become [1,5].

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

Explanation: The input order does not matter; the output is sorted by start.

Example 3
Input: intervals = [[1,2],[2,3]]
Output: [[1,3]]

Explanation: Touching endpoints merge.

Constraints

  • 1 <= intervals.length <= 10^4
  • intervals[i].length == 2
  • 0 <= start <= end <= 10^4

Follow-up: If the intervals arrive one at a time and you must keep the merged set up to date, what data structure would you use?

💡 Hint 1

If the intervals were sorted by start, which intervals could possibly overlap the current one?

💡 Hint 2

After sorting, walk the list keeping the last merged interval. The next interval either starts at or before its end (extend it) or after its end (start a new one).

💡 Hint 3

When extending, the new end is the max of the two ends, since one interval may sit completely inside another.

/**
 * @param {number[][]} intervals
 * @return {number[][]}
 */
function merge(intervals) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc