Skip to content

Instantly share code, notes, and snippets.

@vrachieru
Created October 5, 2014 21:26
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save vrachieru/5649bce26004d8a4682b to your computer and use it in GitHub Desktop.
Save vrachieru/5649bce26004d8a4682b to your computer and use it in GitHub Desktop.
Merge overlapping intervals
/* Merge overlapping intervals
*
* Example:
* [[1,4],[3,5],[2,4],[7,10]] -> [[1,5],[7,10]]
*/
function mergeIntervals(intervals) {
// test if there are at least 2 intervals
if(intervals.length <= 1)
return intervals;
var stack = [];
var top = null;
// sort the intervals based on their start values
intervals = intervals.sort();
// push the 1st interval into the stack
stack.push(intervals[0]);
// start from the next interval and merge if needed
for (var i = 1; i < intervals.length; i++) {
// get the top element
top = stack[stack.length - 1];
// if the current interval doesn't overlap with the
// stack top element, push it to the stack
if (top[1] < intervals[i][0]) {
stack.push(intervals[i]);
}
// otherwise update the end value of the top element
// if end of current interval is higher
else if (top[1] < intervals[i][1])
{
top[1] = intervals[i][1];
stack.pop();
stack.push(top);
}
}
return stack;
}
@bennlich
Copy link

lines 35 and 36 can be removed I think

@kirilgorbachov
Copy link

kirilgorbachov commented Jul 11, 2016

Fails with this input: [[1,3],[2,6],[8,10],[15,18]]
You need to use custom sort function, instead of using default.

Solution:

intervals = intervals.sort(function (startValue, endValue) {
    if (startValue[0] > endValue[0]) {
      return 1;
    }
    if (startValue[0] < endValue[0]) {
      return -1;
    }
    return 0;
  });

@mc-cabe
Copy link

mc-cabe commented Jun 19, 2018

this sort function (standard) works well too

intervals.sort(function(a, b) {
return a[0] - b[0]
})

@reddy27
Copy link

reddy27 commented May 27, 2019

ES6 : intervals.sort((a, b) => a[0] - b[0])

@SkyTik
Copy link

SkyTik commented Dec 17, 2020

You save my day, thanks

@adi518
Copy link

adi518 commented Mar 12, 2021

ES6 : intervals.sort((a, b) => a[0] - b[0])

Can go even further:

intervals.sort(([a0], [b0]) => a0 - b0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment