Problem 43
Merge Intervals
Medium · 20 pts · Array, Sorting
Problem
You are given N closed intervals [start, end]. Two intervals overlap if they share at least one point, so [1, 3] and [3, 5] overlap. Merge all overlapping intervals until no two of the remaining intervals overlap, and print the result sorted by start. Sort the intervals by start. Then go through them in order: if an interval starts at or before the end of the last merged interval, extend that interval's end; otherwise begin a new merged interval.
Input
First line: integer N. Next N lines: two integers start and end.
Output
Print each merged interval on its own line as: start end.
Constraints
1 <= N <= 10000; 0 <= start <= end <= 1000000
Example input
4 1 3 2 6 8 10 15 18
Example output
1 6 8 10 15 18
Explanation
Sorted by start, the intervals are [1,3], [2,6], [8,10] and [15,18]. [2,6] starts inside [1,3], so they merge into [1,6]. [8,10] and [15,18] do not touch anything else, so the result is 1 6, 8 10 and 15 18.