/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, return the median value of the combined sorted 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 have O(log(m+n)) time complexity, where m and n are the lengths of arr_a and arr_b respectively.

Example 1

Input: arr_a = [2, 5], arr_b = [3, 8, 10]

Output: 5.0

Explanation: Merged array: [2, 3, 5, 8, 10], median is 5.

Example 2

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

Output: 2.0

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

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 = [0, 1, 2], arr_b = [3, 4, 5]

Expected: 2.5

Case 2

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

Expected: 4.0

Case 3

Input: arr_a = [], arr_b = [1]

Expected: 1.0

Case 4

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

Expected: 1.0

Case 5

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

Expected: 0.0