AceYourInterviews
Checking sign-in…

36. Insert Interval

IntermediateThree-phase insertion into a closed interval union

Add the new interval to the existing collection, merging it with every interval it overlaps. Return a sorted, disjoint representation of the resulting covered region.

The new interval may overlap several existing intervals or none at all. Closed endpoints that touch must be merged according to this contract.

Example 1

Input

intervals=[[1,3],[6,9]], inserted=[2,5]

Output

[[1,5],[6,9]]

Explanation: The new interval overlaps the first component but ends before the second begins.

Example 2

Input

intervals=[[1,2],[4,5],[7,9]], inserted=[2,7]

Output

[[1,9]]

Explanation: Closed endpoints at 2 and 7 join all three components through the inserted range.

Constraints

  • 0 <= intervals.length <= 105
  • intervals[i].length == 2
  • -231 <= start <= end <= 231 - 1
  • inserted.length == 2
  • Input intervals are sorted by start and strictly disjoint. Endpoints are closed, so touching intervals merge.
Hints
Hint 1

Which old intervals are provably before the insertion?

Hint 2

How far can one growing active end absorb consecutive intervals?

Hint 3

Copy before, merge overlaps, emit once, then copy after.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Bridge several closed components

[[1,2],[4,5],[7,9]]
[2,7]
[[1,9]]