Intervals Merging and scheduling
507. Insert Interval
You are given a list intervals, where intervals[i] = [start, end], sorted by start. No two of them
overlap: each interval ends before the next one starts. You are also given one more interval,
newInterval.
Add newInterval to the list. If it overlaps any of the intervals, merge them all into one interval. Return
the new list, sorted by start, with no two intervals overlapping.
An interval covers every number from its start to its end, both included. Two intervals overlap when they
share at least one point. So [1,3] and [3,5] overlap, while [1,2] and [3,4] do not.
Example 1
Input: intervals = [[1, 2], [4, 6], [8, 10], [13, 15]]
newInterval = [5, 9]
[[1,2],[4,10],[13,15]]Explanation: [5,9] overlaps [4,6] and [8,10], so the three become [4,10]. The other two intervals stay as they
are.
Example 2
Input: intervals = [[1, 3], [6, 8]], newInterval = [3, 6]
[[1,8]]Explanation: [3,6] shares the point 3 with the first interval and the point 6 with the second, so all three merge.
Example 3
Input: intervals = [], newInterval = [-4, 7]
[[-4,7]]Explanation: The list is empty, so the answer holds only the new interval.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ intervals.length ≤ 105intervals[i].length = 2andnewInterval.length = 2-109 ≤ start ≤ end ≤ 109for every interval,newIntervalincludedintervalsis sorted by start, andintervals[i][1] < intervals[i + 1][0].
Clarifying questions
What you would ask an interviewer before writing any code.