Leetcode 57 Insert Interval
Initially, the interval we are trying to merge in is newInterval
, as we loop through the array, it might change depending on the current interval’s start
and end
values. We either merge the 2 intervals , OR we move on to the next interval in the array and also update the interval we are trying to insert.
Note before the final return statement, we need to push the last interval we are trying to insert into the result array.
Solution
/**
* @param {number[][]} intervals
* @param {number[]} newInterval
* @return {number[][]}
*/
var insert = function(intervals, newInterval) {
let result = []
let [ currentL, currentR ] = newInterval;
let i = 0;
while(i < intervals.length) {
const l = intervals[i][0];
const r = intervals[i][1];
if(currentL > r) {
result.push(intervals[i]);
} else if(currentL === r) {
currentL = l;
} else if(currentR < l) {
result.push([currentL, currentR]);
currentL = l;
currentR = r;
} else if(currentR === l) {
currentR = r;
} else if(currentL >= l && currentR >= r) {
currentL = l
} else if(currentL >= l && currentR <= r) {
currentL = l;
currentR = r;
} else if(currentL <= l && currentR <= r) {
currentR = r
}
i++
}
result.push([currentL, currentR]);
return result;
};
The time complexity is O(n)
. Space complexity is O(1)
if you don’t count the result array, O(n)
if counted.