← All Exercises
Merge Overlapping Intervals (Python)
intermediatepython
Background
Calendar blocks, IP ranges, and booking windows all need normalization; sorting by start makes overlap detection a single comparison with the last merged interval.
Problem
Given intervals as [start, end] pairs with start <= end, merge all overlapping or touching intervals and return the resulting disjoint intervals sorted by start. Reject malformed pairs where start > end.
Input
A list of [start, end] integer pairs.
Output
A sorted list of merged [start, end] pairs.
Sample tests
Sample 1
Input: intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
Expected: [[1, 6], [8, 10], [15, 18]]
Sample 2
Input: intervals = [[1, 4], [4, 5]]
Expected: [[1, 5]]
Sample 3
Input: intervals = []
Expected: []
Your solution
Learning objective
Normalize interval sets with a sort-then-sweep strategy and reason about closed endpoints.