Merge Intervals⚓︎
Description⚓︎
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 1:
- Input:
intervals = [[1,3],[2,6],[8,10],[15,18]]
- Output:
[[1,6],[8,10],[15,18]]
- Explanation:
Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
Example 2:
- Input:
intervals = [[1,4],[4,5]]
- Output:
[[1,5]]
- Explanation:
Intervals [1,4] and [4,5] are considered overlapping.
Constraints:
1 <= intervals.length <= 10^4
intervals[i].length == 2
0 <= start_i <= end_i <= 10^4
Solution⚓︎
- Time complexity: \(O(n\log n)\);
- Space complexity: \(O(n)\).
Another way of writing:
Algorithm Explanation:
- Sorting the Intervals:
- The first step involves sorting the
intervals
array. Thesort()
function, by default, sorts the array in ascending order based on the first element of each interval. If the first elements are equal, it sorts based on the second element. This step is crucial as it arranges the intervals in a sequence where potentially overlapping intervals are placed next to each other, simplifying the merging process.
- The first step involves sorting the
- Initializing Variables:
- Two variables
left
andright
are initialized with the first interval's start and end points, respectively. These variables are used to track the current interval being formed or merged.
- Two variables
- Iterating Through the Intervals:
- The algorithm iterates through the intervals starting from the second interval. For each interval, it checks if the current interval's start point (
intervals[i][0]
) is greater than theright
of the interval being formed. If true, this indicates that the current interval does not overlap with the interval being formed, and hence, the formed interval is pushed into the result arrayres
. Theleft
andright
are then updated to the current interval's values, starting the formation of a new interval. - If the current interval's start is not greater than
right
, it means the current interval overlaps with the interval being formed. Theright
is then updated to the maximum of the currentright
and the end point of the current interval (intervals[i][1]
), effectively merging the intervals.
- The algorithm iterates through the intervals starting from the second interval. For each interval, it checks if the current interval's start point (
- Final Interval Addition:
- After the loop, the last formed or merged interval is added to the result array
res
. This step is necessary because the last interval formed by the iteration process has not yet been added to the result array.
- After the loop, the last formed or merged interval is added to the result array
Another way of writing: