mediumGreedyArrayIntervals

Insert Interval

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

Signals to notice

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

Brute force first

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.

The key insight

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.

What must stay true

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.

Easy way to go wrong

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