Insert Interval

Medium Intervals AI round

intervals is a list of intervals, each [start, end] with start ≤ end, holding every point from its start to its end, both ends included. The intervals are in order of their starts, and no two of them overlap or even touch: each one starts after the one before it ends.

Put newInterval, also [start, end], among them. Where it overlaps intervals of the list, even at a single end point, join it and them into one interval, from the smallest start to the largest end.

Return the new list of intervals, still in order of their starts, with no two of them overlapping.

Example 1

Input: intervals = [[2,4],[7,9],[11,13],[16,20]], newInterval = [8,12]
Output: [[2,4],[7,13],[16,20]]

[8, 12] overlaps [7, 9] and [11, 13], so the three join into [7, 13]. [2, 4] ends before it starts and [16, 20] starts after it ends, so they stay as they are.

Example 2

Input: intervals = [[1,5],[10,14]], newInterval = [5,10]
Output: [[1,14]]

[5, 10] touches [1, 5] at 5 and [10, 14] at 10. A shared end point is enough, so all three join into [1, 14].

Example 3

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

Constraints

  • 0 ≤ intervals.length ≤ 10⁵
  • intervals[i] = [start, end] and newInterval = [start, end], with 0 ≤ start ≤ end ≤ 10⁹
  • Each interval in intervals starts after the one before it ends

Watch the explanation

More Intervals

All Intervals problems