Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created August 15, 2020 11:43
Show Gist options
  • Save RP-3/149101d7fb071c7573aec15398125301 to your computer and use it in GitHub Desktop.
Save RP-3/149101d7fb071c7573aec15398125301 to your computer and use it in GitHub Desktop.
/**
* @param {number[][]} intervals
* @return {number}
*/
var eraseOverlapIntervals = function(intervals) {
intervals.sort((a, b) => a[0] - b[0]); // asc by start time
let [result, slow, fast] = [0, 0, 1];
while(fast < intervals.length){
let [s, f] = [intervals[slow], intervals[fast]];
if(s[1] > f[0] && f[1] > s[0]){ // overlaps
result++; // count a deletion
if(intervals[slow][1] <= intervals[fast][1]){
// delete the fast one
fast++;
}else{
// delete the slow one
slow = fast;
fast++;
}
}else{ // no overlap
slow = fast; // catch up the flow with the fast
fast++; // and march the fast steadily on, one step ahead
}
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment