
Leetcode Problem 57: Insert Interval
You are given an array of non-overlapping, sorted intervals where intervals[i] = [start, end], and a new interval newInterval = [start, end]. Insert the new interval into the existing array such that:
You may return a new array rather than modifying in-place.
Visual Example:
Before insertion:
[1--2] [3----5] [6-7] [8----10] [12------16]
Insert [4,8]:
[1--2] [3----5] [6-7] [8----10] [12------16]
[4----------8]
(overlaps with [3,5], [6,7], [8,10])
After insertion and merging:
[1--2] [3--------10] [12------16]
Constraints:
[start, end]start <= endstart <= endfunction insert(intervals: number[][], newInterval: number[]): number[][] {
const result = []
let i = 0
while (i < intervals.length && intervals[i][1] < newInterval[0]) {
result.push(intervals[i++])
}
while (i < intervals.length && intervals[i][0] <= newInterval[1]) {
newInterval[0] = Math.min(intervals[i][0], newInterval[0])
newInterval[1] = Math.max(intervals[i][1], newInterval[1])
i++
}
result.push(newInterval)
while (i < intervals.length) {
result.push(intervals[i++])
}
return result
};