You are given several integer arrays, each sorted in non-decreasing order. Return the median of all of their elements taken together.
The question was first asked for exactly two sorted arrays, and the follow-up asked for the same result when there are many input arrays. Implement the general version: the function receives any number of arrays, and two arrays is the original question.
Function Signature
def median_of_sorted_arrays(arrays: list[list[int]]) -> float:
Rules
-
Let
N
be the total number of elements across all arrays, and let
merged
be all of those elements in sorted order, with duplicates kept.
-
If
N
is odd, the median is
merged[N // 2]
. If
N
is even, the median is
(merged[N // 2 - 1] + merged[N // 2]) / 2
.
-
Return the median as a float, for example
3.0
rather than
3
. Every possible median is an integer or an integer plus one half, so the result is exact.
-
Any individual array may be empty, but there is at least one element in total.
Constraints
-
1 <= len(arrays) <= 10^4
-
0 <= len(arrays[i])
for every
i
, and
1 <= N <= 2 * 10^5
-
Each
arrays[i]
is sorted in non-decreasing order.
-
-10^9 <= arrays[i][j] <= 10^9
Examples
Example 1
Input: arrays = [[1, 4], [2, 9]]
Output: 3.0
All elements in order are [1, 2, 4, 9]. N = 4 is even, so the median is the average of 2 and 4.
Example 2
Input: arrays = [[-3, 5, 5], [0]]
Output: 2.5
All elements in order are [-3, 0, 5, 5], and the average of 0 and 5 is 2.5.
Example 3
Input: arrays = [[-5, 0, 7], [], [2, 2, 9], [4, 10, 11]]
Output: 4.0
All elements in order are [-5, 0, 2, 2, 4, 7, 9, 10, 11]. N = 9 is odd, so the median is the element at index 4, which is 4. The empty array contributes nothing.