Skip to contentKEEP THE CRAFTTHE SANCTUARY

Merge Intervals

Sort intervals by start, then extend the last merged interval or start a new one.

The problem

Implement Solution.merge(intervals). Each interval is a list [start, end] with start <= end. Merge every group of overlapping intervals and return the merged intervals sorted by start, so that no two of them overlap and they cover exactly the same numbers as the input. Intervals that only touch, such as [1, 4] and [4, 5], also overlap and become [1, 5]. If intervals is empty, return an empty list. intervals has up to 10,000 entries.

Starter code

class Solution:
    def merge(self, intervals):
        pass

Public examples

  1. intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]gives[[1, 6], [8, 10], [15, 18]]
  2. intervals = [[1, 4], [4, 5]]gives[[1, 5]]
  3. intervals = [[7, 7], [1, 2], [4, 5]]gives[[1, 2], [4, 5], [7, 7]]
Open it in the practice book
One thought at a time.