← All Exercises

Merge Overlapping Intervals (Java)

basicjava~20min

Background

Calendar and booking systems need normalized ranges. Sorting first reduces merging to a single linear sweep, which is easier than repeated pairwise checks.

Problem

Given a list of closed intervals, merge every pair that overlaps or touches, return the disjoint intervals sorted by start, and reject invalid ranges.

Input

A list of Interval records with start <= end; intervals are closed, so [1,3] and [3,5] overlap and must merge.

Output

A list of merged intervals sorted by start with no overlaps; constructing an invalid interval throws IllegalArgumentException.

Sample tests

Sample 1

Input: [8,10], [1,3], [2,6], [15,18], [17,20]
Expected: [1, 6]
[8, 10]
[15, 20]

Sample 2

Input: [1,3] and [3,5]
Expected: [1, 5]

Your solution

Learning objective

Normalize closed intervals with a sort-and-sweep algorithm and enforce invariants in a record constructor.