All problems

Problem 370

Interval List Intersections

Medium · 20 pts · Array, Two Pointers

Problem

You are given two lists of closed intervals. Within each list the intervals are disjoint and sorted. Find the intersection of the two lists: every interval of points that is covered by both lists. An intersection can be a single point, like [5, 5]. Walk through both lists with two pointers; at each step, the interval that ends first can never intersect anything else, so move past it.

Input

The first list (a line with N, then N lines 'start end'), followed by the second list in the same format.

Output

Print each intersection interval on its own line as: start end, or NONE if there are none.

Constraints

0 <= N, M <= 1000; 0 <= start <= end <= 1000000000

Example input

4
0 2
5 10
13 23
24 25
4
1 5
8 12
15 24
25 26

Example output

1 2
5 5
8 10
15 23
24 24
25 25

Explanation

The intervals [0, 2] and [1, 5] share [1, 2]; [5, 10] and [1, 5] share just the point [5, 5]; and so on for the rest of the two lists.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Insert Interval Next: Longest Harmonious Subsequence