TRT
Sign in
mediumAdvancedLeetCode#sort by start#extend the last

Merge intervals

Merge all overlapping intervals after sorting them by start, in one pass.

The Runtime Theory Team1 min read
Taught inIntervals and sweepingPro — members onlySort intervals by start and most interval problems become a single pass: merging overlaps, inserting a new interval, or sweeping through start and end events to count how many intervals overlap at once.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inintervals = [[1, 3], [2, 6], [8, 10], [15, 18]]

out[[1, 6], [8, 10], [15, 18]]

inintervals = [[1, 4], [4, 5]]

out[[1, 5]]

inintervals = [[1, 10], [2, 3]]

out[[1, 10]]

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

  1. Sort by start.
  2. If the next interval starts at or before the last merged end, set the end to the maximum of the two ends.
  3. Otherwise append it as a new merged interval.
  4. 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.

Not started

Sign in to save your learning progress.

Sign in to save