Start learning free

LESSON 552 OF 673 · INTERVALS

Merge Intervals in Python: Sort and Sweep in O(n log n)

Practice O(n log n) Read the full explanation

You get a list of intervals. Each interval is a pair [starti, endi]. It covers every point from its start to its end.

Merge the intervals that overlap. Return a list of the intervals you end up with, sorted by start.

Two intervals overlap if they share at least one point. Intervals that only touch count too. For example, [2,5] and [5,6] share the point 5. They become [2,6].

 

Example 1:

Input: intervals = [[5,8],[1,3],[7,11],[13,14]]
Output: [[1,3],[5,11],[13,14]]
Explanation: The input is not sorted.
[5,8] and [7,11] share 7 and 8.
They become [5,11].
[1,3] and [13,14] overlap no other interval.

Example 2:

Input: intervals = [[2,5],[5,6],[9,9]]
Output: [[2,6],[9,9]]
Explanation: [2,5] and [5,6] touch at 5.
That is enough to merge them.
[9,9] is a single point.
It stays on its own.

Example 3:

Input: intervals = [[3,20],[4,6],[10,12]]
Output: [[3,20]]
Explanation: [4,6] and [10,12] lie inside [3,20].
All three merge into [3,20].
It ends at 20, not at 12.

 

Constraints:

  • 1 to 100,000 intervals, in any order.
  • Each start and end is a whole number from 0 to 1,000,000.
  • No start is greater than its end.

Note:

Your algorithm should run in O(n log n) time, where n is the number of intervals.

STEP 1 OF 7
    Ctrl + Enter to check

    PYTHON · INTERVALS

    Merge Intervals in Python, explained

    Problem overview

    The method merge receives a list intervals of [start, end] lists. It merges every group of overlapping intervals and returns the intervals that remain, sorted by start. Two intervals overlap when they share at least one point, so intervals that only touch, like [1, 4] and [4, 5], merge into [1, 5]. The input isn't sorted, and it holds between 1 and 100,000 intervals. The statement asks for O(n log n) time.

    For [[1, 3], [2, 6], [8, 10], [15, 18]] the result is [[1, 6], [8, 10], [15, 18]]: the first two overlap and the others stand alone.

    Approach: sort by start, then extend the last interval

    Checking every pair and merging repeatedly is slow and awkward. Sorting makes the problem simple: after sorting by start, the intervals that overlap come one after another. Sweep through them while keeping a list of merged intervals. The last merged interval is the one still growing, and the next interval either:

    • starts after it ends, so it can't overlap anything merged so far and begins a new merged interval, or
    • starts at or before its end, so it overlaps, and the last merged interval is stretched to cover it.

    Sorting costs O(n log n) and the sweep is one pass.

    Step by step

    1. Sort intervals by start with sort and key=lambda interval: interval[0].
    2. Create an empty list merged. Its last interval is the one that may still grow.
    3. Loop over intervals and unpack each one into start and end, so the body doesn't need [0] or [1].
    4. Test whether this interval begins a new one: merged is empty (not merged), or merged[-1][1] < start, meaning the last merged interval ends before this one starts. Use <, not <=, because touching intervals merge.
    5. Append [start, end] to merged in that case. It is now the newest merged interval.
    6. Otherwise extend the last interval: set merged[-1][1] to max(merged[-1][1], end). Keep the larger end, since an interval can lie completely inside the last one, like [2, 3] inside [1, 10], and then the end must stay 10.
    7. Return merged. It is in order of start, as the problem asks.

    The solution in Python

    class Solution:
        def merge(self, intervals: List[List[int]]) -> List[List[int]]:
            intervals.sort(key=lambda interval: interval[0])
            merged = []
            for start, end in intervals:
                if not merged or merged[-1][1] < start:
                    merged.append([start, end])
                else:
                    merged[-1][1] = max(merged[-1][1], end)
            return merged
    

    Here is the sweep on [[6, 8], [1, 9], [2, 4], [4, 7]]. After sorting the list is [[1, 9], [2, 4], [4, 7], [6, 8]], and merged evolves like this:

    startendmerged afterwards
    19[[1, 9]]
    24[[1, 9]]
    47[[1, 9]]
    68[[1, 9]]

    Every interval fits inside [1, 9], so the answer is [[1, 9]].

    Python details worth knowing:

    • sort() reorders the caller's list and returns None; sorted() would return a new list instead.
    • Unpacking. for start, end in intervals assigns the two numbers of each inner list to two names. It works because every inner list has exactly two items.
    • Negative indexes. merged[-1] is the last item. On an empty list it raises IndexError, which is why not merged comes first: or stops at the first true operand, so merged[-1] is never evaluated for an empty list.
    • Why [start, end] and not the original list. The solution appends a new list, so extending merged[-1][1] changes the new list and not the caller's inner lists.

    Complexity

    Time: O(n log n) for the sort plus O(n) for the sweep. Space: O(n) for merged in the worst case, when nothing overlaps (not counting the sort's internal buffer).

    Edge cases and common mistakes

    • Touching intervals. [[1, 4], [4, 5]] gives [[1, 5]]. Using <= in the test would keep them apart.
    • An interval inside another. [[1, 10], [2, 3]] gives [[1, 10]]. Setting the end to end instead of the larger value would shrink the result to [[1, 3]].
    • No overlaps. [[1, 2], [3, 4]] comes back unchanged.
    • A single interval. [[5, 5]] gives [[5, 5]].
    • Same start. [[1, 4], [0, 4]] gives [[0, 4]].
    • Forgetting to sort. The sweep only compares with the last merged interval, so it needs the sorted order. Without the sort, [[1, 3], [8, 10], [2, 6]] gives [[1, 3], [8, 10]], which loses the overlap of [1, 3] and [2, 6]. The correct answer is [[1, 6], [8, 10]].

    Testing

    • [[1, 3], [2, 6], [8, 10], [15, 18]] gives [[1, 6], [8, 10], [15, 18]].
    • [[1, 4], [4, 5]] gives [[1, 5]].
    • [[6, 8], [1, 9], [2, 4], [4, 7]] gives [[1, 9]].
    • [[1, 2], [3, 4]] gives [[1, 2], [3, 4]].
    • [[1, 4], [0, 0]] gives [[0, 0], [1, 4]].
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free