Problem

Given a set of non-overlapping & sorted intervals, insert a new interval into the intervals (merge if necessary).

Example :
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].

JavaScript code

var Interval = function (s, e) {
    this.start = s;
    this.end = e;
}
 
function insert(intervals, newInterval) {
  var result = [];
 
  for(var i=0; i<intervals.length; i++){
      var interval = intervals[i];
        if(interval.end < newInterval.start){
              result.push(interval);
        }else if(interval.start > newInterval.end){
              result.push(newInterval);
              newInterval = interval;        
        }else if(interval.end >= newInterval.start || interval.start <= newInterval.end){
              newInterval = new Interval(Math.min(interval.start, newInterval.start), Math.max(newInterval.end, interval.end));
        }
  }
 
  result.push(newInterval); 
 
  return result;
}

var intevs = [new Interval(1,3), new Interval(7,10), new Interval(9,15)];

console.log(insert(intevs, new Interval(3,5)));

0 comments:

Blogroll

Follow this blog by Email

Popular Posts