All problems

Problem 104

Median of Two Sorted Arrays

Hard · 30 pts · Array, Binary Search, Divide and Conquer

Problem

You are given two sorted arrays with N and M elements. Print the median of all N + M elements combined. If the total count is odd, the median is the middle value of the combined sorted list. If it is even, the median is the average of the two middle values. Print the median with exactly one digit after the decimal point (it is always a whole number or a half). Merging the arrays takes O(N + M) and is fast enough; the classic challenge is O(log(min(N, M))) by binary searching for a split of the two arrays.

Input

First line: integer N. Second line: N sorted integers. Third line: integer M. Fourth line: M sorted integers. (N or M may be 0, in which case its line is empty.)

Output

Print the median with exactly one digit after the decimal point.

Constraints

0 <= N, M <= 100000; 1 <= N + M; -1000000 <= values <= 1000000

Example input

2
1 3
1
2

Example output

2.0

Explanation

Combining 1 3 and 2 gives 1 2 3. The total count 3 is odd, so the median is the middle value 2, printed as 2.0.

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

Previous: Contains Nearby Duplicate Next: Koko Eating Bananas