Given closed intervals, merge all that overlap (including ones that only touch) and return the result.
Before you code
After sorting by start, an interval can only overlap the merged interval just before it.
Hints
- Sort by start.
- If the next interval starts at or before the last merged end, set the end to the maximum of the two ends.
- Otherwise append it as a new merged interval.
- Here intervals are closed, so [1, 4] and [4, 5] merge.
Production & complexity notes
When solving Merge intervals on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Intervals and sweeping to reinforce the underlying pattern.
What it practices
Sort, then one pass, from Intervals and sweeping.