← All Exercises

Merging Overlapping Intervals

basicjavascript~10min

Background

Interval merging calendars, IP ranges, and genomic regions. The sort-then-sweep formulation is the standard linear pass after sorting.

Problem

Given a list of closed intervals [start, end], merge all intervals that overlap or touch at endpoints into their union and output the resulting disjoint intervals sorted by start. Output the merged list.

Input

A JSON object {"intervals": [number, number][]} where start <= end for every interval.

Output

A JSON object {"merged": [number, number][]} sorted by start with no overlapping or touching entries.

Sample tests

Sample 1

Input: {"intervals":[[1,3],[2,6],[8,10],[15,18]]}
Expected: {"merged":[[1,6],[8,10],[15,18]]}

Sample 2

Input: {"intervals":[[1,4],[4,5]]}
Expected: {"merged":[[1,5]]}

Sample 3

Input: {"intervals":[[5,7],[1,3],[2,4]]}
Expected: {"merged":[[1,4],[5,7]]}

Your solution

Learning objective

Master the sort-and-sweep pattern for interval union problems.