cswork / OAOpen practice workspace

JPMorgan ChaseOA #20

Merge Intervals

Estimated MediumJudge-ready

Topics (AI-labelled)Prefix & Ranges

Merge overlapping closed intervals and output the non-overlapping intervals in ascending order of start. Touching at the same endpoint counts as overlapping, but adjacent integer endpoints that are not equal do not. The original example input contains [1,23], so the correct result is [[1,23]]; the original output was mistakenly computed as if it were [1,2].

Input

The first line contains n, followed by n lines of start end; 1≤n≤100000, 1≤start≤end≤1000000000. The original constraint intervals[i][2] is a typo involving the endpoint index; it is restored as bounds on the two endpoints.

Output

The first line is the number of merged intervals, followed by one line per interval with its two endpoints, in ascending order of start.

Example 1

Input:

4
7 7
2 3
6 11
1 23

Output:

1
1 23

Example 2

Input:

3
1 2
2 3
5 5

Output:

2
1 3
5 5

Example 3

Input:

2
1 1
2 2

Output:

2
1 1
2 2

Example notes

The outputs of the three public examples are, in order: 1 / 1 23; 2 / 1 3 / 5 5; 2 / 1 1 / 2 2. These answers have been checked by independent enumeration or direct simulation.

Editorial

Loading solution…