Merge Overlapping Intervals using C++.


Problem statement

Given a set of time intervals in any order, merge all overlapping intervals into one and output the result which should have only mutually exclusive intervals

Given set of interval is {{12, 14}, {11, 13}, {20, 22}, {21, 23}} then

  • Interval {12, 14} and {11, 13} overlap with each other hence merge them as {11, 14}

  • Interval {20, 22} and {21, 23} overlap with each other hence merge them as {20, 23}

Algorithm

1. Sort the intervals based on increasing order of starting time
2. Push the first interval on to a stack
3. For each interval perform below steps:
   3.1. If the current interval does not overlap with the top of the stack, push it.
   3.2. If the current interval overlaps with top of the stack and ending time of current interval is more than that of top of stack, update stack top with the ending time of current interval.
4. Finally, stack contains the merged intervals.

Example

#include <iostream>
#include <algorithm>
#include <stack>
#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))
using namespace std;
struct interval{
   int start;
   int end;
};
bool compareInterval(interval i1, interval i2){
   return (i1.start < i2.start);
}
void mergeOverlappingIntervals(interval *arr, int n){
   if (n <= 0) {
      return;
   }
   stack<interval> s;
   sort(arr, arr + n, compareInterval);
   s.push(arr[0]);
   for (int i = 1; i < n; ++i) {
      interval top = s.top();
      if (top.end < arr[i].start) {
         s.push(arr[i]);
      } else if(top.end < arr[i].end) {
         top.end = arr[i].end;
         s.pop();
         s.push(top);
      }
   }
   cout << "Merged intervals: " << endl;
   while (!s.empty()) {
      interval i = s.top();
      cout << "{" << i.start << ", " << i.end << "}" << " ";
      s.pop();
   }
   cout << endl;
}
int main(){
   interval arr[] = {{12, 14}, {11, 13}, {20, 22}, {21, 23}};
   mergeOverlappingIntervals(arr, SIZE(arr));
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

Merged intervals:
{20, 23} {11, 14}

Updated on: 31-Oct-2019

478 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements