Insert Interval

MediumIntervals and Sweep Line

You are given a list of closed intervals intervals, sorted by start and disjoint (no two of them share a point), and one more closed interval newInterval = [start, end].

Insert newInterval into the list, merging it with every interval it overlaps (shares at least one point with), so that the list is still sorted by start and disjoint. Return the resulting list.

You can build and return a new array; you don't have to modify intervals in place.

Constraints

  • 0 <= intervals.length <= 10^4
  • intervals is sorted by start and its intervals are disjoint.
  • 0 <= start <= end <= 10^5 for every interval, including newInterval.

Examples

Example 1

Input: intervals = [[1,2],[5,8],[10,12]], newInterval = [3,4]
Output: [[1,2],[3,4],[5,8],[10,12]]

[3, 4] overlaps nothing, so it goes into the gap between [1, 2] and [5, 8].

Example 2

Input: intervals = [[1,3],[4,6],[8,10],[12,15]], newInterval = [5,9]
Output: [[1,3],[4,10],[12,15]]

[5, 9] overlaps [4, 6] and [8, 10]. All three merge into [4, 10].

Example 3

Input: intervals = [], newInterval = [4,7]
Output: [[4,7]]

Inserting into an empty list leaves just the new interval.

JavaScript you'll use: Arrays: create, read, update Destructuring, spread and rest

/**
 * @param {number[][]} intervals
 * @param {number[]} newInterval
 * @return {number[][]}
 */
function insert(intervals, newInterval) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.