mediumGreedySortingGreedy

Merge Intervals

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

Recognize the pattern

merge overlapping intervalssort by startextend or start new

Brute force idea

A straightforward first read of Merge Intervals is this: Compare every pair for overlap. Doesn't exploit sorted structure. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

Better approach

The real unlock in Merge Intervals comes when you notice this: Sort by start time. Scan left to right: if the current interval overlaps with the last merged one, extend it. Otherwise, start a new merged interval. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

The compass for Merge Intervals is this: After sorting by start, overlapping intervals are adjacent. If the current start ≤ the previous end, they overlap — merge by extending the end to max(prevEnd, currEnd). As long as that statement keeps holding, you can trust the steps built on top of it.

Watch out for

A common way to get lost in Merge Intervals is this: Not taking the max of ends when merging — if interval B is entirely contained within interval A, the merged end should be A's end, not B's. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Greedy Pattern