CodingNodes / Intervals / Merge Intervals System design Space play · ←→ step · R restart

Problem

Each element of intervals is a range [start, end] on a number line. Combine every group of ranges that overlap (including ranges that only touch at a single point) into one range covering the whole group.

Return the resulting ranges with no two overlapping, ordered by start. The input may arrive in any order.

Constraints

  • 1 ≤ intervals.length ≤ 10⁴
  • intervals[i].length == 2
  • 0 ≤ start ≤ end ≤ 10⁴

Examples: pick one to animate

Solutions

TimeO(n log n) SpaceO(n)

Time: Sorting costs O(n log n); the merging pass visits each range once.

Space: The merged list can hold up to n ranges when nothing overlaps (not counting the sort's own working space).

Sort by start so overlapping ranges sit next to each other. Keep a list of merged ranges. For each range, compare its start with the end of the last merged range: if it starts at or before that end, the two overlap, so stretch the last end to the larger of the two ends. Otherwise it begins a new merged range.