Merge Intervals
Merge Intervals
IntervalsArraysSorting
Problem Statement
Given an array of intervals
where intervals[i] = [start_i, end_i]
, merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example
Example 1:
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Initial Intervals:
[1, 3]
[2, 6]
[8, 10]
[15, 18]
Result:
[1, 6]
[8, 10]
[15, 18]
Output: [[1,6],[8,10],[15,18]]
Solution
To merge overlapping intervals, we first need to sort them by their start time. This ensures that we can process them in order and easily identify overlaps with the most recently processed interval.
Algorithm Steps
- Sort the intervals based on their start times.
- Initialize a result list with the first interval.
- Iterate through the rest of the intervals.
- If the current interval overlaps with the last one in the result list, merge them by updating the end of the last interval.
- Otherwise, add the current interval to the result list.
Intervals
[1, 6]
[8, 10]
[2, 6]
[15, 18]
Merged Result
Start with the unsorted intervals.
Merge Intervals Solution