mediumGreedyArrayIntervals

Insert Interval

mediumTime: O(n)Space: O(n)

Recognize the pattern

insert a new interval into sorted non-overlapping intervalsmerge if overlappingthree phases

Brute force idea

If you approach Insert Interval in the most literal way possible, you get this: Add the interval, re-sort, then merge. Doesn't exploit the already-sorted structure. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

Better approach

The deeper shift in Insert Interval is this: Three phases: (1) add all intervals that end before newInterval starts (no overlap). (2) Merge all overlapping intervals with newInterval. (3) Add all intervals that start after newInterval ends. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Key invariant

At the center of Insert Interval is one steady idea: The intervals are already sorted and non-overlapping. The new interval can only overlap with a contiguous run of existing intervals — everything before and after is independent. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

The trap in Insert Interval usually looks like this: Not merging transitively — the new interval might overlap with multiple existing intervals. Keep extending the merge while overlap exists. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Intervals Pattern