778. Merge overlapping time intervals
GPU reservations, log windows and annotated text spans all reduce to the same task: merge ranges that overlap so you can measure total covered time.
Write merge_intervals(intervals) for a list of [start, end] pairs with start <= end, in any order. Merge any intervals that overlap or touch (end of one equals start of the next). Return the merged list sorted by start.
def merge_intervals(intervals)Example 1
Input: merge_intervals([[5, 8], [1, 3], [2, 4], [8, 9]])
Output: [[1, 4], [5, 9]]
Example 2
Input: intervals = []
Output: []
Example 3
Input: intervals = [[1, 10], [2, 3], [4, 5]]
Output: [[1, 10]]
Constraints
- At most 100,000 intervals.
- Integers, start <= end.
Hint 1
Sort first.
Hint 2
Compare with the last merged interval only.
Hint 3
Extend with max, not with the new end.
Common mistakes
- Overwriting the end instead of taking the max, which shrinks blocks.
- Treating touching intervals as separate when the task says to merge them.
Understand the idea
Merging intervals is a sort then sweep. Once intervals are sorted by start, you only ever compare the next interval with the last merged one. If it starts before that one ends, they overlap and you extend; if not, there is a gap and you start a new block. [1, 3] and [2, 4] become [1, 4]; [5, 8] and [8, 9] touch and become [5, 9]. The same sweep computes total GPU hours booked, merges overlapping entity spans in NER labels, and finds free slots in a calendar.