codebrew.ai
Medium
Intervals

Merge Intervals

Sort by start, then merge any interval that overlaps the last one kept.

Approach

Sort intervals by start time. Walk through them, and if the current interval starts before the previous merged one ends, extend that merged interval's end; otherwise push a new interval. One sort plus one sweep.

Time complexity

O(n log n)

Space complexity

O(n)

Common mistake

Forgetting to sort first — merging only works once intervals are ordered by start.

See it run, step by step

Generate an interactive lesson for Merge Intervals — trace every variable and watch the algorithm execute until it clicks.

Start a lesson on Merge Intervals

Related problems