Given a collection of intervals where each interval is represented as a pair [start, end]
, merge all overlapping intervals. If intervals overlap, you need to merge them into one interval.
Input/Output Examples
plaintext
Example 1:
Input: [[1, 3], [2, 6], [8, 10], [15, 18]]
Output: [[1, 6], [8, 10], [15, 18]]
Explanation: Intervals [1, 3] and [2, 6] overlap and are merged into [1, 6]. The other intervals do not overlap.
Example 2:
Input: [[1, 4], [4, 5]]
Output: [[1, 5]]
Explanation: Intervals [1, 4] and [4, 5] overlap and are merged into [1, 5].
Approach to Merge Overlapping Intervals
- Sort the intervals:
- First, sort the intervals based on their starting times.
- Iterate through the sorted intervals:
- Compare each interval with the last merged interval. If the current interval overlaps with the last merged interval, update the end of the last merged interval to the maximum of the current interval's end and the last merged interval's end.
- If the current interval does not overlap, add it as a new merged interval.
- Edge Case:
- If the input has only one interval or no intervals, no merging is needed.
C++ Program to Merge Overlapping Intervals
cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Function to merge overlapping intervals
vector<vector<int>> mergeIntervals(vector<vector<int>>& intervals) {
if (intervals.empty()) return {};
// Sort intervals based on the starting times
sort(intervals.begin(), intervals.end());
vector<vector<int>> merged;
// Add the first interval
merged.push_back(intervals[0]);
// Iterate through the sorted intervals
for (int i = 1; i < intervals.size(); i++) {
// Get the last interval in the merged list
vector<int>& last = merged.back();
// If the current interval overlaps with the last interval, merge them
if (intervals[i][0] <= last[1]) {
last[1] = max(last[1], intervals[i][1]);
} else {
// If not, add the current interval to the merged list
merged.push_back(intervals[i]);
}
}
return merged;
}
int main() {
vector<vector<int>> intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
vector<vector<int>> result = mergeIntervals(intervals);
cout << "Merged Intervals: " << endl;
for (const auto& interval : result) {
cout << "[" << interval[0] << ", " << interval[1] << "]" << endl;
}
return 0;
}
Java Program to Merge Overlapping Intervals
java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MergeIntervals {
// Function to merge overlapping intervals
public static int[][] mergeIntervals(int[][] intervals) {
if (intervals.length <= 1) {
return intervals;
}
// Sort intervals based on the starting times
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
List<int[]> merged = new ArrayList<>();
// Add the first interval
merged.add(intervals[0]);
// Iterate through the sorted intervals
for (int i = 1; i < intervals.length; i++) {
int[] lastInterval = merged.get(merged.size() - 1);
// If the current interval overlaps with the last interval, merge them
if (intervals[i][0] <= lastInterval[1]) {
lastInterval[1] = Math.max(lastInterval[1], intervals[i][1]);
} else {
// If not, add the current interval to the merged list
merged.add(intervals[i]);
}
}
return merged.toArray(new int[merged.size()][]);
}
public static void main(String[] args) {
int[][] intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
int[][] result = mergeIntervals(intervals);
System.out.println("Merged Intervals: ");
for (int[] interval : result) {
System.out.println(Arrays.toString(interval));
}
}
}
Python Program to Merge Overlapping Intervals
python
# Function to merge overlapping intervals
def merge_intervals(intervals):
if not intervals:
return []
# Sort intervals based on the starting times
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
# Iterate through the sorted intervals
for i in range(1, len(intervals)):
last_interval = merged[-1]
# If the current interval overlaps with the last interval, merge them
if intervals[i][0] <= last_interval[1]:
last_interval[1] = max(last_interval[1], intervals[i][1])
else:
# If not, add the current interval to the merged list
merged.append(intervals[i])
return merged
# Example usage
if __name__ == "__main__":
intervals = [[1, 3], [2, 6], [8, 10], [15, 18]]
result = merge_intervals(intervals)
print("Merged Intervals:")
for interval in result:
print(interval)
Time Complexity:
- O(n log n): Sorting the intervals takes O(n log n), and iterating through them takes O(n), so the overall time complexity is dominated by the sorting step.
Space Complexity:
- O(n): We use a list to store the merged intervals, which can hold up to
n
intervals in the worst case.