Skip to content
BASA DSA

Insert Interval

MediumIntervals

Insert newInterval into sorted, pairwise disjoint closed intervals and merge all overlaps. Return sorted disjoint closed intervals; endpoints that touch count as overlapping.

Example 1

Input
intervals = [[1,3],[7,9]]
newInterval = [2,8]
Output
[[1,9]]

Explanation

The new interval bridges both existing intervals, merging everything into [1,9].

Example 2

Input
intervals = []
newInterval = [4,5]
Output
[[4,5]]

Explanation

No existing intervals means the new interval alone is returned.

Example 3

Input
intervals = [[1,2],[5,6]]
newInterval = [3,4]
Output
[[1,2],[3,4],[5,6]]

Explanation

The new interval lies in the gap, so all three remain separate.

Constraints

  • 0 <= number of intervals <= 10000
  • Each interval is [start,end] with start <= end
  • Existing intervals are sorted and disjoint

Function contractinsertArguments: json, json
Loading draft…
SolutionRuns on your device
Loading draft…