SDE & MLE Prep

56. Merge Intervals

Problem

Merge all overlapping intervals (intervals that merely touch, like [1,4] and [4,5], overlap too) and return the non-overlapping intervals that cover the same ranges.

Example: [[1,3],[2,6],[8,10],[15,18]] → [[1,6],[8,10],[15,18]]

Constraints: up to 10⁴ intervals.

Sort by start; if an interval starts before the last merged one ends, extend; otherwise start a new block.

Complexity: O(n log n).

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        res = []
        for s, e in sorted(intervals):
            if res and s <= res[-1][1]:
                res[-1][1] = max(res[-1][1], e)
            else:
                res.append([s, e])
        return res