Merge Intervals

Medium

Topics
ArraySortingIntervals

Given an array of intervals (each [start, end]), merge all overlapping intervals and return the non-overlapping result sorted by start. On this judge intervals are shown separated by |.

Example 1

118[1,3][2,6][8,10][15,18]merged
Two intervals merge when they touch or overlap, which on this axis means their bars line up vertically. Sorting by start is what makes that a single pass: every interval either extends the one being built or starts a new one. 4 in, 3 out.
Each lane is one interval drawn on a shared axis, so overlaps line up vertically.
Input:  grid = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]

Example 2

15[1,4][4,5]merged
Input:  grid = [[1,4],[4,5]]
Output: [[1,5]]

Constraints

  • 1 <= intervals.length <= 10^4
  • intervals[i].length == 2
Editorial — intuition, approach, complexity and pitfalls

Intuition

Once sorted by start, overlapping intervals are adjacent. Walk through and extend the current merged interval whenever the next one starts before the current end.

Approach

  1. Sort intervals by start.
  2. Keep a running merged interval; if the next starts within it, extend the end to the max.
  3. Otherwise push the current and start a new one.

Dry Run

intervals = [1,3] [2,6] [8,10] [15,18]      (already in start order)
  [1,3]     nothing merged yet              ->  open a new interval [1,3]
  [2,6]     starts at 2, current end is 3   ->  2 <= 3, extend to [1,6]
  [8,10]    starts at 8, current end is 6   ->  8 > 6, open [8,10]
  [15,18]   starts at 15, current end is 10 ->  open [15,18]
answer [1,6] [8,10] [15,18]
Taking max(current end, e) rather than just e is the detail that matters, because
the next interval can be entirely INSIDE the current one. On [[1,5],[2,3],[4,8]]
the correct answer is [[1,8]], but a plain assignment gives [[1,3],[4,8]]: the
[1,5] is truncated to [1,3], and then [4,8] no longer looks like an overlap at
all. One wrong assignment produces two wrong intervals.
The comparison is <=, which is the opposite of meeting-rooms where it is strict.
Both are right for their own question. Here touching intervals should merge --
[1,4] and [4,5] become [1,5] -- because the task is covering a range. There,
touching meetings are compatible, because the task is occupying a room.
Sorting is what makes a single backward glance sufficient: after it, anything
that overlaps the interval being built must start at or before its end, so the
only candidate is the immediately previous merged interval.

Complexity

  • Time — O(n log n): sort plus a linear merge.
  • Space — O(n): the output list.

Common Pitfalls

  • Extend using max of ends — the next interval may be fully inside the current one.

Full Solution — all languages

class Solution:
    def merge(self, grid):
        intervals=grid; intervals.sort()
        res=[]
        for s,e in intervals:
            if res and s<=res[-1][1]:
                res[-1][1]=max(res[-1][1],e)
            else:
                res.append([s,e])
        return res
SensAI
Beta
Tap the mic to stop voice mode