4. Median of Two Sorted Arrays
Asked at 41Bloomberg79Amazon77Microsoft75Google74Meta70Apple63Rippling100Goldman Sachs80tcs63Zoho60eBay53Infosys45Zenefits100Yahoo97Dropbox92Adobe86Okta71GE Healthcare70Autodesk69Cognizant69VMware69Qualcomm68Zeta64Samsung63Capgemini62Arcesium61Accenture61Walmart Labs60Palo Alto Networks59Sprinklr54DE Shaw53Oracle52Tesla52Yandex49Flipkart43PayPal42Nvidia39Uber35IBM35Salesforce28TikTok26
Problem
Return the median of the union of two sorted arrays nums1 and nums2 (the mean of the two middle values when the total count is even). Aim for O(log(m + n)).
Example: [1,3] and [2] → 2.0; [1,2] and [3,4] → 2.5
Binary search a cut in the shorter array A at i, with cut j = half − i in B. The cut is correct when A[i-1] ≤ B[j] and B[j-1] ≤ A[i]; then the median comes from the four border values.
A: 1 3 | 8 9 left part: {1,3,2,4,5} right: {8,9,7,10,...}
B: 2 4 5 | 7 10 maxLeft = 5, minRight = 7
Complexity: O(log min(m, n)).
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
A, B = (nums1, nums2) if len(nums1) <= len(nums2) else (nums2, nums1)
m, n = len(A), len(B)
half = (m + n + 1) // 2
lo, hi = 0, m
while True:
i = (lo + hi) // 2
j = half - i
al = A[i - 1] if i else float("-inf")
ar = A[i] if i < m else float("inf")
bl = B[j - 1] if j else float("-inf")
br = B[j] if j < n else float("inf")
if al <= br and bl <= ar:
if (m + n) % 2:
return float(max(al, bl))
return (max(al, bl) + min(ar, br)) / 2
if al > br:
hi = i - 1
else:
lo = i + 1
assert Solution().findMedianSortedArrays([1, 3], [2]) == 2.0
assert Solution().findMedianSortedArrays([1, 2], [3, 4]) == 2.5
assert Solution().findMedianSortedArrays([], [1]) == 1.0
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] A = nums1.length <= nums2.length ? nums1 : nums2, B = A == nums1 ? nums2 : nums1;
int m = A.length, n = B.length, half = (m + n + 1) / 2, lo = 0, hi = m;
while (true) {
int i = (lo + hi) / 2, j = half - i;
int al = i > 0 ? A[i - 1] : Integer.MIN_VALUE, ar = i < m ? A[i] : Integer.MAX_VALUE;
int bl = j > 0 ? B[j - 1] : Integer.MIN_VALUE, br = j < n ? B[j] : Integer.MAX_VALUE;
if (al <= br && bl <= ar) {
if ((m + n) % 2 == 1) return Math.max(al, bl);
return (Math.max(al, bl) + (double) Math.min(ar, br)) / 2;
}
if (al > br) hi = i - 1; else lo = i + 1;
}
}
}
func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
A, B := nums1, nums2
if len(A) > len(B) {
A, B = B, A // binary search the shorter array
}
m, n := len(A), len(B)
half := (m + n + 1) / 2
lo, hi := 0, m
for {
i := (lo + hi) / 2 // i elements from A, j from B on the left side
j := half - i
al, ar, bl, br := math.MinInt, math.MaxInt, math.MinInt, math.MaxInt
if i > 0 {
al = A[i-1]
}
if i < m {
ar = A[i]
}
if j > 0 {
bl = B[j-1]
}
if j < n {
br = B[j]
}
if al <= br && bl <= ar {
if (m+n)%2 == 1 {
return float64(max(al, bl))
}
return float64(max(al, bl)+min(ar, br)) / 2
}
if al > br {
hi = i - 1
} else {
lo = i + 1
}
}
}