Merge Overlapping Intervals
Last Updated :
20 Aug, 2024
Given a set of time intervals in any order, our task is to merge all overlapping intervals into one and output the result which should have only mutually exclusive intervals.
Example:
Input: arr = {{1,3},{2,4},{6,8},{9,10}}
Output: {{1, 4}, {6, 8}, {9, 10}}
Explanation: Given intervals: [1,3],[2,4],[6,8],[9,10], we have only two overlapping intervals here,[1,3] and [2,4]. Therefore we will merge these two and return [1,4],[6,8], [9,10].
Input: arr = {{6,8},{1,9},{2,4},{4,7}}
Output: {{1, 9}}
Naive O(n^2)
A simple approach is to start from the first interval and compare it with all other intervals for overlapping, if it overlaps with any other interval, then remove the other interval from the list and merge the other into the first interval. Repeat the same steps for the remaining intervals after the first. This approach cannot be implemented in better than O(n^2) time.
To solve this problem optimally we have to first sort the intervals according to the starting time. Once we have the sorted intervals, we can combine all intervals in a linear traversal. The idea is, in sorted array of intervals, if arr[i] doesn’t overlap with arr[i-1], then arr[i+1] cannot overlap with arr[i-1] because starting time of arr[i+1] must be greater than or equal to arr[i].
Follow the steps mentioned below to implement the approach:
- Sort the intervals based on the increasing order of starting time.
- Push the first interval into a stack.
- For each interval do the following:
- If the current interval does not overlap with the top of the stack then, push the current interval into the stack.
- If the current interval overlap with the top of the stack then, update the stack top with the ending time of the current interval.
- The end stack contains the merged intervals.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int>> mergeOverlap(vector<vector<int>>& arr) {
// Sort intervals based on start values
sort(arr.begin(), arr.end());
vector<vector<int>> res;
res.push_back(arr[0]);
for (int i = 1; i < arr.size(); i++) {
vector<int>& last = res.back();
vector<int>& curr = arr[i];
// If current overlaps with the last
// merged, merge them
if (curr[0] <= last[1])
last[1] = max(last[1], curr[1]);
else // Add current to the result
res.push_back(curr);
}
return res;
}
// Driver Code
int main() {
vector<vector<int>> arr = {{6, 8}, {1, 9}, {2, 4}, {4, 7}};
vector<vector<int>> res = mergeOverlap(arr);
cout << "The Merged Intervals are: ";
for (const vector<int>& interval : res) {
cout << "[" << interval[0] << ", " << interval[1] << "] ";
}
cout << endl;
return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static List<int[]> mergeOverlap(int[][] arr) {
// Sort intervals based on start values
Arrays.sort(arr, (a, b) -> Integer.compare(a[0], b[0]));
List<int[]> res = new ArrayList<>();
res.add(arr[0]);
for (int i = 1; i < arr.length; i++) {
int[] last = res.get(res.size() - 1);
int[] curr = arr[i];
// If current overlaps with the last merged, merge them
if (curr[0] <= last[1]) {
last[1] = Math.max(last[1], curr[1]);
} else {
// Add current to the result
res.add(curr);
}
}
return res;
}
// Driver Code
public static void main(String[] args) {
int[][] arr = {{6, 8}, {1, 9}, {2, 4}, {4, 7}};
List<int[]> res = mergeOverlap(arr);
System.out.print("The Merged Intervals are: ");
for (int[] interval : res) {
System.out.print("[" + interval[0] + ", " + interval[1] + "] ");
}
System.out.println();
}
}
Python
def merge_overlap(arr):
# Sort intervals based on start values
arr.sort(key=lambda x: x[0])
res = [arr[0]]
for i in range(1, len(arr)):
last = res[-1]
curr = arr[i]
# If current overlaps with the last
# merged, merge them
if curr[0] <= last[1]:
last[1] = max(last[1], curr[1])
else:
# Add current to the result
res.append(curr)
return res
# Driver Code
if __name__ == "__main__":
arr = [[6, 8], [1, 9], [2, 4], [4, 7]]
res = merge_overlap(arr)
print("The Merged Intervals are: ", end="")
for interval in res:
print(f"[{interval[0]}, {interval[1]}]", end=" ")
print()
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static List<int[]> MergeOverlap(int[][] arr)
{
// Sort intervals based on start values
Array.Sort(arr, (a, b) => a[0].CompareTo(b[0]));
List<int[]> res = new List<int[]>();
res.Add(arr[0]);
for (int i = 1; i < arr.Length; i++)
{
int[] last = res[res.Count - 1];
int[] curr = arr[i];
// If current overlaps with the last merged, merge them
if (curr[0] <= last[1])
{
last[1] = Math.Max(last[1], curr[1]);
}
else
{
// Add current to the result
res.Add(curr);
}
}
return res;
}
// Driver Code
static void Main(string[] args)
{
int[][] arr = new int[][] {
new int[] { 6, 8 },
new int[] { 1, 9 },
new int[] { 2, 4 },
new int[] { 4, 7 }
};
List<int[]> res = MergeOverlap(arr);
Console.Write("The Merged Intervals are: ");
foreach (int[] interval in res)
{
Console.Write("[" + interval[0] + ", " + interval[1] + "] ");
}
Console.WriteLine();
}
}
JavaScript
function mergeOverlap(arr) {
// Sort intervals based on start values
arr.sort((a, b) => a[0] - b[0]);
let res = [arr[0]];
for (let i = 1; i < arr.length; i++) {
let last = res[res.length - 1];
let curr = arr[i];
// If current overlaps with the last
// merged, merge them
if (curr[0] <= last[1]) {
last[1] = Math.max(last[1], curr[1]);
} else {
// Add current to the result
res.push(curr);
}
}
return res;
}
// Driver Code
let arr = [[6, 8], [1, 9], [2, 4], [4, 7]];
let res = mergeOverlap(arr);
console.log("The Merged Intervals are:");
res.forEach(interval => {
console.log(`[${interval[0]}, ${interval[1]}]`);
});
OutputThe Merged Intervals are: [1, 9]
Time complexity: O(n log n)
Auxiliary Space: O(n)
In-Place Using Sort
The above solution requires O(n) extra space for the stack. We can avoid the use of extra space by doing merge operations in place. Below are detailed steps.
Follow the steps mentioned below to implement the approach:
- Sort all intervals in increasing order of start time.
- Traverse sorted intervals starting from the first interval,
- Do the following for every interval.
- If the current interval is not the first interval and it overlaps with the previous interval,
then merge it with the previous interval. Keep doing it while the interval overlaps with the previous one. - Otherwise, Add the current interval to the output list of intervals.
Below is the implementation of the above approach:
C++14
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Merge overlapping intervals in-place. We return
// modified size of the array arr.
int mergeOverlap(vector<vector<int>>& arr) {
// Sort intervals based on start values
sort(arr.begin(), arr.end());
int resIdx = 0; // Index of the last merged
for (int i = 1; i < arr.size(); i++) {
// If current interval overlaps with the
// last merged interval
if (arr[resIdx][1] >= arr[i][0])
arr[resIdx][1] = max(arr[resIdx][1], arr[i][1]);
// Move to the next interval
else {
resIdx++;
arr[resIdx] = arr[i];
}
}
// Returns size of the merged intervals
return (resIdx + 1);
}
// Driver Code
int main() {
vector<vector<int>> arr = {{6, 8}, {1, 9}, {2, 4}, {4, 7}};
// Get the new size of the array after merging
int newSize = mergeOverlap(arr);
// Print the merged intervals based on the new size
cout << "The Merged Intervals are: ";
for (int i = 0; i < newSize; i++) {
cout << "[" << arr[i][0] << ", " << arr[i][1] << "] ";
}
cout << endl;
return 0;
}
C
// C program to merge overlapping Intervals in
// O(n Log n) time and O(1) extra space.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
// An Interval
typedef struct Interval {
int s, e;
} Interval;
// Function used in sort
int mycomp(const void* a, const void* b)
{
Interval* data_1 = (Interval*)a;
Interval* data_2 = (Interval*)b;
return (data_1->s - data_2->s);
}
// Find maximum between two numbers.
int max(int num1, int num2)
{
return (num1 > num2) ? num1 : num2;
}
void mergeIntervals(Interval arr[], int n)
{
// Sort Intervals in increasing order of
// start time
qsort(arr, n, sizeof(Interval), mycomp);
int index = 0; // Stores index of last element
// in output array (modified arr[])
// Traverse all input Intervals
for (int i = 1; i < n; i++) {
// If this is not first Interval and overlaps
// with the previous one
if (arr[index].e >= arr[i].s) {
// Merge previous and current Intervals
arr[index].e = max(arr[index].e, arr[i].e);
}
else {
index++;
arr[index] = arr[i];
}
}
// Now arr[0..index-1] stores the merged Intervals
printf("\n The Merged Intervals are: ");
for (int i = 0; i <= index; i++)
printf("[%d, %d]", arr[i].s, arr[i].e);
}
// Driver program
int main()
{
Interval arr[]
= { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } };
int n = sizeof(arr) / sizeof(arr[0]);
mergeIntervals(arr, n);
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
Java
import java.util.Arrays;
public class Main {
// Merge overlapping intervals in-place and return
// the new size of the array
public static int mergeOverlap(int[][] arr) {
// Sort intervals based on start values
Arrays.sort(arr, (a, b) -> Integer.compare(a[0], b[0]));
int resIdx = 0; // Index of the last merged interval
for (int i = 1; i < arr.length; i++) {
// If current interval overlaps with the last merged interval
if (arr[resIdx][1] >= arr[i][0]) {
arr[resIdx][1] = Math.max(arr[resIdx][1], arr[i][1]);
} else {
// Move to the next interval
resIdx++;
arr[resIdx] = arr[i];
}
}
// Return the size of the merged intervals
return resIdx + 1;
}
// Driver Code
public static void main(String[] args) {
int[][] arr = { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } };
// Get the new size of the array after merging
int newSize = mergeOverlap(arr);
// Print the merged intervals based on the new size
System.out.print("The Merged Intervals are: ");
for (int i = 0; i < newSize; i++) {
System.out.print("[" + arr[i][0] + ", " + arr[i][1] + "] ");
}
System.out.println();
}
}
Python
def merge_overlap(arr):
# Sort intervals based on start values
arr.sort(key=lambda x: x[0])
res_idx = 0 # Index of the last merged interval
for i in range(1, len(arr)):
# If current interval overlaps with
# the last merged interval
if arr[res_idx][1] >= arr[i][0]:
arr[res_idx][1] = max(arr[res_idx][1], arr[i][1])
else:
# Move to the next interval
res_idx += 1
arr[res_idx] = arr[i]
# Return the size of the merged intervals
return res_idx + 1
# Driver Code
if __name__ == "__main__":
arr = [[6, 8], [1, 9], [2, 4], [4, 7]]
# Get the new size of the array after merging
new_size = merge_overlap(arr)
# Print the merged intervals based on the new size
print("The Merged Intervals are:", end=" ")
for i in range(new_size):
print(f"[{arr[i][0]}, {arr[i][1]}]", end=" ")
print()
C#
using System;
using System.Collections.Generic;
public class GfG
{
public static int MergeOverlap(int[][] arr)
{
// Sort intervals based on start values
Array.Sort(arr, (a, b) => a[0].CompareTo(b[0]));
int resIdx = 0; // Index of the last merged interval
for (int i = 1; i < arr.Length; i++)
{
// If current interval overlaps with the last merged interval
if (arr[resIdx][1] >= arr[i][0])
{
arr[resIdx][1] = Math.Max(arr[resIdx][1], arr[i][1]);
}
else
{
// Move to the next interval
resIdx++;
arr[resIdx] = arr[i];
}
}
// Return the size of the merged intervals
return resIdx + 1;
}
public static void Main()
{
int[][] arr = new int[][] {
new int[] { 6, 8 },
new int[] { 1, 9 },
new int[] { 2, 4 },
new int[] { 4, 7 }
};
// Get the new size of the array after merging
int newSize = MergeOverlap(arr);
// Print the merged intervals based on the new size
Console.WriteLine("The Merged Intervals are:");
for (int i = 0; i < newSize; i++)
{
Console.WriteLine("[" + arr[i][0] + ", " + arr[i][1] + "]");
}
}
}
JavaScript
function mergeOverlap(arr) {
// Sort intervals based on start values
arr.sort((a, b) => a[0] - b[0]);
let resIdx = 0; // Index of the last merged interval
for (let i = 1; i < arr.length; i++) {
// If current interval overlaps with the last merged interval
if (arr[resIdx][1] >= arr[i][0]) {
arr[resIdx][1] = Math.max(arr[resIdx][1], arr[i][1]);
} else {
// Move to the next interval
resIdx++;
arr[resIdx] = arr[i];
}
}
// Return the size of the merged intervals
return resIdx + 1;
}
// Driver Code
const arr = [[6, 8], [1, 9], [2, 4], [4, 7]];
// Get the new size of the array after merging
const newSize = mergeOverlap(arr);
// Print the merged intervals based on the new size
console.log("The Merged Intervals are:");
for (let i = 0; i < newSize; i++) {
console.log(`[${arr[i][0]}, ${arr[i][1]}]`);
}
Output The Merged Intervals are: [1, 9]
Time Complexity: O(n log n)
Auxiliary Space Complexity: O(1)