Insert Interval

MediumIntervals

You get a list of intervals, each [start, end], sorted by start and with no two overlapping, and one more interval, newInterval. Add newInterval to the list, merging it with every interval it overlaps, and return the new list.

The answer must also be sorted by start with no overlaps. Two intervals that only touch, like [1, 3] and [3, 6], count as overlapping and merge into [1, 6].

Examples

Example 1
Input:  intervals = [[1, 2], [4, 6], [9, 12]], newInterval = [5, 8]
Output: [[1, 2], [4, 8], [9, 12]]

[5, 8] overlaps [4, 6] only, and the two become [4, 8].

Example 2
Input:  intervals = [[2, 3], [5, 7], [8, 10], [13, 15]], newInterval = [6, 14]
Output: [[2, 3], [5, 15]]

[6, 14] reaches into three intervals, from [5, 7] to [13, 15], and swallows all of them.

Constraints

  • 0 ≤ intervals.length ≤ 10⁴
  • 0 ≤ start ≤ end ≤ 10⁵ for every interval, newInterval too.
  • intervals is sorted by start and has no overlaps.

Stuck?

Hint 1

The list falls into three runs: intervals that end before newInterval starts, intervals that overlap it, and intervals that start after it ends.

Hint 2

Copy the first run as it is. Grow newInterval over the second run (smallest start, largest end), push it, then copy the third run.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur