This is a task taken from Leetcode -
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] /** Explanation: Since intervals `[1,3]` and `[2,6]` overlap, merge them into `[1,6]`. */
Example 2:
Input: [[1,4],[4,5]] Output: [[1,5]] /** Explanation: Intervals `[1,4]` and `[4,5]` are considered overlapping. */
My imperative solution -
/**
* @param {number[][]} intervals
* @return {number[][]}
*/
var merge = function(intervals) {
const sortedIntervals = intervals.sort((a,b) => a[0] - b[0]);
const newIntervals = [];
for (let i = 0; i < intervals.length; i++) {
if (!newIntervals.length || newIntervals[newIntervals.length - 1][1] < sortedIntervals[i][0]) {
newIntervals.push(sortedIntervals[i]);
} else {
newIntervals[newIntervals.length - 1][1] = Math.max(newIntervals[newIntervals.length - 1][1], sortedIntervals[i][1]);
}
}
return newIntervals;
};
My functional solution -
/**
* @param {number[][]} intervals
* @return {number[][]}
*/
function merge(intervals) {
const mergeInterval = (ac, x) => (!ac.length || ac[ac.length - 1][1] < x[0]
? ac.push(x)
: ac[ac.length - 1][1] = Math.max(ac[ac.length - 1][1], x[1]), ac);
return intervals
.sort((a,b) => a[0] - b[0])
.reduce(mergeInterval, []);
};