Medium Sorting

Merge Intervals

Receives a list of [start, end] integer intervals, in any order, and returns the minimal set of non-overlapping intervals covering exactly the same points, sorted by start. It first copies and sorts the intervals by their start value — which guarantees that any interval overlapping something already emitted must overlap the most recent one — and then walks the sorted list once, keeping the last emitted range open: an interval whose start falls at or before that range's end is absorbed into it (extending its end only when it reaches further), while an interval that starts after it opens a new range. Touching intervals such as [1, 3] and [3, 5] count as overlapping. Returns the merged intervals as a new list, never mutating the caller's array; an empty input returns an empty list.

Visualization

Input

Algorithm code

Custom input

Saved inputs

References