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.
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].
Input: intervals = [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considered overlapping.
start_i
always ≤ end_i
)?For the purposes of our solution, we will assume intervals can be out of order, intervals are always valid, and we will address edge cases in our implementation.
Overall time complexity: O(n log n).
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> merge(vector<vector<int>>& intervals) {
// Edge case: if there are no intervals, return an empty vector
if (intervals.empty()) {
return {};
}
// Sort intervals by their starting point
sort(intervals.begin(), intervals.end());
// Vector to hold the merged intervals
vector<vector<int>> merged;
// Start with the first interval as the initial interval to merge
merged.push_back(intervals[0]);
// Iterate through the rest of the intervals
for (auto i = 1; i < intervals.size(); ++i) {
// Get the last merged interval
auto& lastMerged = merged.back();
// Compare current interval with the last merged interval
if (intervals[i][0] <= lastMerged[1]) {
// There is an overlap, so we merge the intervals
lastMerged[1] = max(lastMerged[1], intervals[i][1]);
} else {
// No overlap, so we add the current interval to the result
merged.push_back(intervals[i]);
}
}
return merged;
}
intervals
array based on the starting value of each interval. This is achieved using the built-in sort
function.merged
vector and add the first interval to it.merged
vector.
intervals[i][0] <= lastMerged[1]
), we merge them by updating the end of the last merged interval (lastMerged[1] = max(lastMerged[1], intervals[i][1])
).merged
vector.Thus, our total time complexity is O(n log n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?