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;
}
@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