Algo-Sim › Binary Search
Median of Two Sorted Arrays
Hard · Binary Search · step through it in Java, Python and C++ on your own input
Find the median of two sorted arrays in O(log min(m, n)) by binary searching where to cut the shorter array.
Problem
Given two sorted arrays a and b of sizes m and n, return the median of all m + n values combined: the middle value, or the average of the two middle values when the total is even. The required time is O(log(m + n)).
Constraints
- 0 ≤ m, n ≤ 1000 and 1 ≤ m + n ≤ 2000
- -10⁶ ≤ a[i], b[i] ≤ 10⁶
- Both arrays are sorted
- Merging is O(m + n); the target is logarithmic
Edge cases to test
- One array empty
- Total length even vs odd
- All of one array smaller than the other
Follow-up questions
- Why search the shorter array?
- The cut in the shorter one fixes the cut in the longer one, and keeps the index range valid: O(log min(m, n)).
- How do you find the k-th smallest of two sorted arrays?
- Discard k/2 elements from the array whose k/2-th value is smaller, recursively: O(log k).
- What about the running median of a stream?
- Two heaps: a max-heap for the low half, a min-heap for the high half: O(log n) per insert (LC 295).
Solution
Java
public double findMedianSortedArrays(int[] a, int[] b) {
if (a.length > b.length) return findMedianSortedArrays(b, a);
int m = a.length, n = b.length, half = (m + n + 1) / 2;
int lo = 0, hi = m;
while (lo <= hi) {
int i = (lo + hi) / 2, j = half - i;
int aLeft = i == 0 ? Integer.MIN_VALUE : a[i - 1];
int aRight = i == m ? Integer.MAX_VALUE : a[i];
int bLeft = j == 0 ? Integer.MIN_VALUE : b[j - 1];
int bRight = j == n ? Integer.MAX_VALUE : b[j];
if (aLeft <= bRight && bLeft <= aRight) {
if ((m + n) % 2 == 1) return Math.max(aLeft, bLeft);
return (Math.max(aLeft, bLeft) + Math.min(aRight, bRight)) / 2.0;
} else if (aLeft > bRight) {
hi = i - 1;
} else {
lo = i + 1;
}
}
throw new IllegalArgumentException("inputs must be sorted");
}Python
def find_median_sorted_arrays(a, b):
if len(a) > len(b): return find_median_sorted_arrays(b, a)
m, n = len(a), len(b)
half = (m + n + 1) // 2
lo, hi = 0, m
while lo <= hi:
i = (lo + hi) // 2
j = half - i
a_left = a[i - 1] if i > 0 else float("-inf")
a_right = a[i] if i < m else float("inf")
b_left = b[j - 1] if j > 0 else float("-inf")
b_right = b[j] if j < n else float("inf")
if a_left <= b_right and b_left <= a_right:
if (m + n) % 2 == 1:
return max(a_left, b_left)
return (max(a_left, b_left) + min(a_right, b_right)) / 2
elif a_left > b_right:
hi = i - 1
else:
lo = i + 1
raise ValueError("inputs must be sorted")C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
double findMedianSortedArrays(vector<int> &a, vector<int> &b) {
if (int(a.size()) > int(b.size()))
return findMedianSortedArrays(b, a);
int m = int(a.size()), n = int(b.size()), half = (m + n + 1) / 2;
int lo = 0, hi = m;
while (lo <= hi) {
int i = (lo + hi) / 2, j = half - i;
int aLeft = i == 0 ? INT_MIN : a[i - 1];
int aRight = i == m ? INT_MAX : a[i];
int bLeft = j == 0 ? INT_MIN : b[j - 1];
int bRight = j == n ? INT_MAX : b[j];
if (aLeft <= bRight && bLeft <= aRight) {
if ((m + n) % 2 == 1)
return std::max(aLeft, bLeft);
return (std::max(aLeft, bLeft) + std::min(aRight, bRight)) / 2.0;
} else if (aLeft > bRight) {
hi = i - 1;
} else {
lo = i + 1;
}
}
throw invalid_argument("inputs must be sorted");
}
};
More Binary Search problems
- Binary Search (Easy)
- Search Insert Position (Easy)
- Sqrt(x) (Easy)
- Find First and Last Position of Element in Sorted Array (Medium)
- Find Minimum in Rotated Sorted Array (Medium)
- Search in Rotated Sorted Array (Medium)
- Find Peak Element (Medium)
- Single Element in a Sorted Array (Medium)
- Koko Eating Bananas (Medium)
- Kth Smallest Element in a Sorted Matrix (Medium)
- Allocate Minimum Pages (Hard)
- Time Based Key-Value Store (Medium)