CodingNodes / Intervals / Insert Interval System design Space play · ←→ step · R restart

Problem

intervals holds ranges [start, end] that are sorted by start and do not overlap each other. You are also given one more range, newInterval.

Insert newInterval so the list stays sorted and non-overlapping, merging it with every existing range it overlaps (ranges that merely touch also count as overlapping). Return the resulting list.

Constraints

  • 1 ≤ intervals.length ≤ 10⁴
  • intervals[i].length == 2 and newInterval.length == 2
  • 0 ≤ start ≤ end ≤ 10⁵
  • intervals is sorted by start and its ranges do not overlap

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: The index i only moves forward through the n ranges, one time in total across the three loops.

Space: The result list holds up to n + 1 ranges (the input is already sorted, so no extra sorting space is needed).

Because the input is sorted, the ranges fall into three groups around the new one: those that end before it starts, those that overlap it, and those that start after it ends. Copy the first group untouched. For the second group, stretch the new range to cover each of them (smaller start, larger end). Add the stretched range, then copy the third group.