Skip to content
DeepForgeby svx
All problems
MediumAlgorithmsal-055

Merge Overlapping Intervals

Problem

Given a list of [start, end] intervals, merge every group that overlaps or touches and return the resulting sorted intervals.

Sort by start time, then extend the last merged interval when the next start is at most its current end, otherwise append it as a new interval. Return an empty list for empty input.

Hint

After sorting by start, a new interval merges whenever its start does not exceed the current merged end.

Test cases

case 1
in: [[[1,3],[2,6],[8,10],[15,18]]]
expected: [[1,6],[8,10],[15,18]]
case 2
in: [[[1,4],[4,5]]]
expected: [[1,5]]
case 3
in: [[]]
expected: []
case 4
in: [[[1,4],[0,4]]]
expected: [[0,4]]
case 5
in: [[[1,4],[2,3]]]
expected: [[1,4]]
Starter codePython
def merge_intervals(intervals):
    # Your code here
    pass

5 test cases · run your code against them in the editor