Insert Interval

Med
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Insert Interval

Approach

Since intervals are already sorted, make three passes: (1) add all intervals ending before the new one starts, (2) merge all intervals overlapping with the new one by extending the new interval's start/end, (3) add all remaining intervals after the merged region.

Complexity Analysis

Time
O(n)
Space
O(n)

Pattern

Sort + Merge (Pre-sorted)

Why It Works

The three-phase approach exploits sorted order: intervals before the new one cannot overlap (they end too early), intervals after cannot overlap (they start too late). Only the middle group overlaps, and we merge them by expanding the new interval to encompass all overlapping ranges.

Updated Feb 2026