problems / 105

Smallest Range Across Lists

medium two-pointers sorting arrays 2000 ms · 256 MB

Smallest Range Across Lists

You are given k sorted lists of integers. Find the narrowest range [a, b] (with a ≤ b) such that every list contains at least one value inside [a, b] (inclusive).

If several ranges achieve the smallest width b − a, output the one with the smallest a.

Values may repeat, both within a single list and across different lists.

Input

The first line contains an integer k (1 ≤ k ≤ 10^5) — the number of lists.

Each of the next k lines describes one list: an integer m_i (1 ≤ m_i), the length of the i-th list, followed by m_i integers in non-decreasing order, each in [−10^9, 10^9] — the elements of the list.

The total number of integers across all lists, Σ m_i, is at most 2·10^5.

Output

Print two integers a and b: the bounds of the narrowest range that contains at least one element from every list, choosing the smallest a among ranges of minimum width.

Notes

In the first example, the range [20, 24] contains 24 from the first list, 20 from the second list, and 22 from the third list, and no narrower range works.

Example 1

Input

3
5 4 10 15 24 26
4 0 9 12 20
4 5 18 22 30

Output

20 24

Example 2

Input

1
4 5 7 7 9

Output

5 5

Hints · reveal one at a time if you're stuck

Hint 1

Merge all the values into one sorted sequence, but keep each value's list id with it. A valid range corresponds to a stretch of this sequence that contains at least one element from every list.

Hint 2

Sweep a window over the sorted sequence: extend the right end, and once every list is represented, move the left end forward as far as it stays valid. Keep a count of how many elements of each list lie in the window, along with how many lists are represented.

Hint 3

Shrink with a loop rather than a single step, because a list with several elements in the window can be trimmed more than once. Since the left end only moves forward, the first window found at the minimum width already has the smallest start, so a strict comparison on width is enough.

report an issue Prefer your own editor? sooks prep 105 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.