Skip to content

Commit 2b8a894

Browse files
authored
Merge pull request #764 from i-priyanshu/master
Added Merge_intervals fixes #763
2 parents 2f7efd1 + 6281c19 commit 2b8a894

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Given a set of time intervals in any order, merge all overlapping intervals
2+
// into one and output the result which should have only mutually exclusive
3+
// intervals. Let the intervals be represented as pairs of integers for
4+
// simplicity. For example, let the given set of intervals be {{1,3}, {2,4},
5+
// {5,7}, {6,8}}. The intervals {1,3} and {2,4} overlap with each other, so they
6+
// should be merged and become {1, 4}. Similarly, {5, 7} and {6, 8} should be
7+
// merged and become {5, 8}.
8+
9+
// Write a function that produces the set of merged intervals for the given set
10+
// of intervals.
11+
12+
#include <bits/stdc++.h>
13+
using namespace std;
14+
struct Interval
15+
{
16+
int start, end;
17+
};
18+
19+
bool compare(Interval i1, Interval i2) { return (i1.start < i2.start); }
20+
21+
void mergeIntervals(Interval arr[], int n)
22+
{
23+
if (n <= 0)
24+
return;
25+
stack<Interval> s;
26+
sort(arr, arr + n, compare);
27+
s.push(arr[0]);
28+
29+
for (int i = 1; i < n; i++)
30+
{
31+
Interval top = s.top();
32+
33+
if (top.end < arr[i].start)
34+
s.push(arr[i]);
35+
36+
else if (top.end < arr[i].end)
37+
{
38+
top.end = arr[i].end;
39+
s.pop();
40+
s.push(top);
41+
}
42+
}
43+
44+
cout << "\n The Merged Intervals are: ";
45+
while (!s.empty())
46+
{
47+
Interval t = s.top();
48+
cout << "[" << t.start << "," << t.end << "] ";
49+
s.pop();
50+
}
51+
return;
52+
}
53+
54+
int main()
55+
{
56+
Interval arr[] = {{1, 3}, {2, 4}, {5, 7}, {6, 8}};
57+
int n = sizeof(arr) / sizeof(arr[0]);
58+
mergeIntervals(arr, n);
59+
return 0;
60+
}

0 commit comments

Comments
 (0)