Problem 369
Insert Interval
Medium · 20 pts · Array, Sorting
Problem
You have a list of non-overlapping closed intervals [start, end], sorted by start. Insert one new interval into the list, merging it with every interval it overlaps or touches, so that the list stays sorted and non-overlapping. Two intervals overlap if they share at least one point, so [1, 3] and [3, 5] merge into [1, 5]. Print the resulting list.
Input
First line: N. Next N lines: start and end of each interval. Last line: start and end of the new interval.
Output
Print each resulting interval on its own line as: start end.
Constraints
0 <= N <= 10000; 0 <= start <= end <= 100000
Example input
2 1 3 6 9 2 5
Example output
1 5 6 9
Explanation
The new interval [2, 5] overlaps [1, 3], so they merge into [1, 5]. The interval [6, 9] does not overlap and stays as it is.