Skip to content

Merge intervals

MediumPython 3ArraysSorting

You are given a list intervals where intervals[i] = [start, end] with start <= end, in no particular order. Merge every pair of overlapping intervals and return the resulting list of non-overlapping intervals sorted by start. Intervals that merely touch (one ends exactly where the next starts) count as overlapping and must be merged.

Constraints:
  - 0 <= len(intervals) <= 10^4
  - starts and ends are integers, start <= end
Examples:
  [[1, 3], [2, 6], [8, 10], [15, 18]] -> [[1, 6], [8, 10], [15, 18]]
  [[1, 4], [4, 5]]                    -> [[1, 5]]     (touching endpoints)
  [[1, 4], [2, 3]]                    -> [[1, 4]]     (fully contained)
  []                                  -> []

Python 3, run in your browser. Run tests runs the problem's own tests with a free account; the AI interviewer reads your code and your runs in a practice interview.

Loading the editor…