Merge intervals#

Levels: level-3
Data structures: array
Patterns: intervals

LeetCode

Description#

  • Given a collection of intervals, merge all overlapping intervals.

Examples#

text
1Input: [[1,3],[2,6],[8,10],[15,18]]
2Output: [[1,6],[8,10],[15,18]]
3Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
text
1Input: [[1,4],[4,5]]
2Output: [[1,5]]
3Explanation: Intervals [1,4] and [4,5] are considered overlapping.

Python Solution#

py
 1from typing import List
 2
 3
 4class Solution:
 5    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
 6
 7        intervals.sort(key=lambda x: x[0])
 8
 9        merged = []
10        for interval in intervals:
11            # if the list of merged intervals is empty or if the current
12            # interval does not overlap with the previous, simply append it.
13            if not merged or merged[-1][1] < interval[0]:
14                merged.append(interval)
15            else:
16                # otherwise, there is overlap, so we merge the current and previous
17                # intervals.
18                merged[-1][1] = max(merged[-1][1], interval[1])
19
20        return merged