 # Merge the intervals of overlapping arrays - Coding Problem

## Merge the intervals.

Suppose there are multiple arrays having overlapping intervals. We need to merge them to avoid all the overlaps.
Real time scenario of this problem is while conducting meetings. Two overlapping meetings can be concluded in the same meeting room, always considering the meeting agendas are totally good to go with each other.

## Solution

Suppose we have four ranges as [2, 4], [3, 6], [8, 14], [16, 19].
To begin the comparison, it is required that the arrays are sorted in ascending order. That will make merging easier and correct.
After sorting is done, let’s compare the first two to check if they can be merged. Let’s store the result of merging in mergedIntervals.
The first element of first array i.e. 2 is the beginning of first-most array. the end range of first array can be the original end range of first array or the end range of second array, depending on whether there is an overlap. In this case, [2, 4] and [3, 6] is overlapping, so these arrays will be merged and the result array will be [2, 6]. Similarly the processing will be done for rest of the arrays.

In above case,

### Implementation

``````function mergeArrayIntervals(intervals) {
let mergedIntervals = [],
last;

intervals.sort(function(a, b) {
return a - b || a - b;
});

intervals.forEach(function(r) {
if (!last || r > last) {
last = r;
mergedIntervals.push(last);
} else if (r > last) last = r;

// console.log(r, JSON.stringify(mergedIntervals));
});

return mergedIntervals;
}
//Input: console.log(mergeIntervals([[2, 4], [3, 6], [8, 14], [16, 19],[17,20]]))
//Output: [[2,6],[8,14],[16,20]]
``````
``````def mergeArrayIntervals(intervals):
sorted(intervals, key = lambda x: (x, x))

mergedIntervals = []
last = None

for r in intervals:
if last is None or r > last:
last = r
mergedIntervals.append(last)
elif r > last: last = r

return mergedIntervals

#print(mergeArrayIntervals([[2, 4], [3, 6], [8, 14], [16, 19],[17,20]]))
``````
``````// third
``````
``````fourth
``````