TRT
Sign in
mediumAdvancedLeetCode#three phases: before, overlapping, after

Insert interval

Insert a new interval into a sorted, non-overlapping list, merging where needed, in O(n).

The Runtime Theory Team1 min read
Taught inIntervals and sweepingPro — members onlySort intervals by start and most interval problems become a single pass: merging overlaps, inserting a new interval, or sweeping through start and end events to count how many intervals overlap at once.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inintervals = [[1, 3], [6, 9]], newInterval = [2, 5]

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

inintervals = [[1, 2], [3, 5], [6, 7], [8, 10], [12, 16]], newInterval = [4, 8]

out[[1, 2], [3, 10], [12, 16]]

inintervals = [], newInterval = [5, 7]

out[[5, 7]]

The intervals are sorted by start and don't overlap. Insert newInterval, merging any overlaps, and return the result.

Before you code

The list is already sorted, so no sort is needed. Intervals fall into three groups: entirely before the new one, overlapping it, and entirely after.

Hints

  1. Copy intervals whose end is before the new start.
  2. Merge every interval that overlaps into the new one: take the minimum start and maximum end.
  3. Append the merged interval, then the rest.

Production & complexity notes

When solving Insert interval on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Intervals and sweeping to reinforce the underlying pattern.

What it practices

Overlap tests on a sorted list, from Intervals and sweeping.

Not started

Sign in to save your learning progress.

Sign in to save