Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created February 25, 2020 05:38
Show Gist options
  • Save RP-3/b2f48d9423b55a7352ff2261de5562d1 to your computer and use it in GitHub Desktop.
Save RP-3/b2f48d9423b55a7352ff2261de5562d1 to your computer and use it in GitHub Desktop.
/**
* @param {number[][]} intervals
* @param {number[]} newInterval
* @return {number[][]}
*/
var insert = function(intervals, newInterval) {
for(let i=0; i<intervals.length; i++){
if(fitsBefore(newInterval, i)){
return intervals.slice(0, i)
.concat([newInterval])
.concat(intervals.slice(i));
}
if(overlaps(newInterval, i)){
const newStart = Math.min(intervals[i][0], newInterval[0]);
let j = i;
while(intervals[j] !== undefined && newInterval[1] >= intervals[j][0]) j++;
j--;
const newEnd = Math.max(newInterval[1], intervals[j][1]);
return intervals.slice(0, i)
.concat([[newStart, newEnd]])
.concat(intervals.slice(j+1));
}
}
// if did not insert during loop
intervals.push(newInterval);
return intervals;
function fitsBefore(tuple, i){
return tuple[1] < intervals[i][0];
}
function overlaps(tuple, i){
return tuple[0] <= intervals[i][1] && tuple[1] >= intervals[i][0];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment