Skip to content

Instantly share code, notes, and snippets.

@mvalipour
Last active November 13, 2016 19:41
Show Gist options
  • Save mvalipour/2fae0d841fee88a6eae689e0ea21d44e to your computer and use it in GitHub Desktop.
Save mvalipour/2fae0d841fee88a6eae689e0ea21d44e to your computer and use it in GitHub Desktop.
function solution(input) {
if (input.length === 0) {
return [];
}
// sort by first element of each interval
// O(n log n)
intervals = input.slice(0);
intervals.sort(([a], [b]) => a - b);
// sweep through intervals and chain them together
// if chain broken, flush into results and continue
// O(n)
var result = [];
var [start, end] = intervals.shift();
intervals.forEach(([s, e]) => {
if (s <= end) {
end = Math.max(e, end);
} else {
result.push([start, end]);
[start, end] = [s, e];
}
});
// the last chain would never be broken, so flush it!
result.push([start, end]);
return result;
}
var tests = [
[[2, 5], [1, 10], [11, 15], [1, 3]],
[],
[[4, 5], [1, 2], [2, 3]],
[[1, 10], [2, 2]]
];
tests.forEach(t => console.log(t, '=>', solution(t)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment