/4. Median of Two Sorted Arrays

4. Median of Two Sorted Arrays

Hard
Arrays46.1% acceptance

Given two sorted integer arrays arr_a and arr_b of lengths m and n respectively, compute the median value of the combined array formed by merging arr_a and arr_b. The median is defined as the middle value if the total number of elements is odd, or the average of the two middle values if the total number of elements is even. The solution must run in O(log(m+n)) time.

Example 1

Input: arr_a = [2, 5], arr_b = [3, 7, 9]

Output: 5.0

Explanation: Merged array: [2, 3, 5, 7, 9], median is 5.

Example 2

Input: arr_a = [0, 1], arr_b = [2, 3, 4, 5]

Output: 2.5

Explanation: Merged array: [0, 1, 2, 3, 4, 5], median is (2+3)/2 = 2.5.

Constraints

  • 1 <= len(arr_a) + len(arr_b) <= 2000
  • 0 <= len(arr_a) <= 1000
  • 0 <= len(arr_b) <= 1000
  • -106 <= arr_a[i], arr_b[i] <= 106
  • arr_a and arr_b are sorted in non-decreasing order
Python (current runtime)

Case 1

Input: arr_a = [1, 4, 6], arr_b = [2, 3, 5]

Expected: 3.5

Case 2

Input: arr_a = [10], arr_b = [20, 30, 40]

Expected: 25.0

Case 3

Input: arr_a = [], arr_b = [7, 8, 9, 10]

Expected: 8.5

Case 4

Input: arr_a = [-5, -2, 0], arr_b = [1, 3, 4, 6]

Expected: 1.0

Case 5

Input: arr_a = [1000], arr_b = [-1000]

Expected: 0.0