GitHub
Medium

Merge Intervals

Given an array of intervals where intervals[i] = [start_i, end_i], merge all overlapping intervals and return an array of non-overlapping intervals.

Write a function that merges all overlapping intervals. An interval [a, b] overlaps with [c, d] if there is some real number x such that a ≤ x ≤ b and c ≤ x ≤ d.

How to Solve

Sort intervals by start time. Iterate through sorted intervals, merging consecutive intervals if the current interval's start is less than or equal to the previous interval's end. Otherwise, add the previous merged interval to the result and start a new one.

Code

Test Cases

Input 1

Expected Output: [[1, 6], [8, 10], [15, 18]] ([1,3] and [2,6] overlap, merged to [1,6])

Input 2

Expected Output: [[1, 5]] (adjacent intervals are merged)

Input 3

Expected Output: [[0, 4]] ([0,4] completely contains [1,4])

Complexity

Time Complexity: O(n log n) - Sorting takes O(n log n), then a single O(n) pass to merge.

Space Complexity: O(n) - In the worst case, no intervals merge, so we store all n intervals in the result array.