Practice · Intervals · 3 of 4

Insert a Range into a Sorted List

You are given intervals, a list of ranges [start, end] sorted by start, in which no two ranges overlap or touch. You are also given one more range, newInterval.

Insert newInterval and return the resulting list of ranges, sorted by start, with any ranges that now overlap merged into one. Ranges that share even a single point overlap, so [1, 3] and [3, 6] merge into [1, 6]. You may build a new list rather than change intervals.

Example 1

Input
intervals = [[1, 2], [4, 5], [7, 9], [12, 14]], newInterval = [5, 8]
Output
[[1, 2], [4, 9], [12, 14]]
[5, 8] touches [4, 5] at 5 and overlaps [7, 9], so the three become [4, 9].

Example 2

Input
intervals = [[1, 3], [8, 10]], newInterval = [4, 6]
Output
[[1, 3], [4, 6], [8, 10]]
Nothing overlaps, so the new range slots in between.

Constraints

  • intervals holds 0 to 10⁴ ranges.
  • Every range, newInterval included, has 0 ≤ start ≤ end ≤ 10⁵.
  • intervals is sorted by start, and each range ends before the next one starts.