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

Javascript
Python
function mergeArrayIntervals(intervals) {
  	let mergedIntervals = [],
		last;
  
	intervals.sort(function(a, b) {
		return a[0] - b[0] || a[1] - b[1];
	});

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

       // 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[0], x[1]))

	mergedIntervals = []
	last = None

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

	return mergedIntervals

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