Merge Intervals Algorithm
The Merge Intervals Algorithm is a widely used technique in computer science and mathematics that deals with the manipulation and merging of overlapping intervals. This algorithm is particularly helpful in situations where you have a collection of intervals, such as time periods or ranges, and you need to combine any overlapping or adjacent intervals into a single, continuous interval. The algorithm takes a list of intervals as input, and outputs a new list of intervals where overlapping intervals are merged into a single interval. The Merge Intervals Algorithm has applications in various domains, such as scheduling, resource allocation, and genomic data analysis.
The core idea behind the Merge Intervals Algorithm is to first sort the input intervals based on their start times. This ensures that the intervals are examined in a sequential manner, making it easier to identify overlaps. After sorting, the algorithm iterates through the intervals and compares the current interval's start time with the previous interval's end time. If the current interval's start time is less than or equal to the previous interval's end time, it indicates an overlap, and the two intervals are merged by updating the end time of the previous interval to the maximum of the end times of the two overlapping intervals. If there is no overlap, the current interval is added to the output list as a separate interval. This process continues until all input intervals have been processed, resulting in a merged list of non-overlapping intervals.
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
inline bool operator < (const Interval& x, const Interval& y) {
if (x.start == y.start) {
return x.end < y.end;
}
return x.start < y.start;
}
class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
vector<Interval> result;
if (intervals.empty()) {
return result;
}
sort(intervals.begin(), intervals.end());
result.push_back(intervals[0]);
for (int i = 1; i < intervals.size(); i++) {
Interval& back = result.back();
if (back.end >= intervals[i].start) {
back.end = max(back.end, intervals[i].end);
} else {
result.push_back(intervals[i]);
}
}
return result;
}
};