Median of Two Sorted Arrays
binary-search • divide-and-conquer • array
Hard
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
Examples
Input
nums1 = [1, 3], nums2 = [2]
Output
2.0
The merged array is [1,2,3] and median is 2.
Input
nums1 = [1,2], nums2 = [3,4]
Output
2.5
The merged array is [1,2,3,4] and median is (2+3)/2 = 2.5.
Solution
Do a binary search on the smaller array to partition both arrays so that left halves and right halves satisfy max(lefts) <= min(rights).
Adjust partition using binary search based on comparisons between partition elements.
When correct partition is found, compute median from neighboring elements. Time complexity is .
Median of Two Sorted Arrays
binary-search • divide-and-conquer • array
Hard
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
Examples
Input
nums1 = [1, 3], nums2 = [2]
Output
2.0
The merged array is [1,2,3] and median is 2.
Input
nums1 = [1,2], nums2 = [3,4]
Output
2.5
The merged array is [1,2,3,4] and median is (2+3)/2 = 2.5.
Solution
Do a binary search on the smaller array to partition both arrays so that left halves and right halves satisfy max(lefts) <= min(rights).
Adjust partition using binary search based on comparisons between partition elements.
When correct partition is found, compute median from neighboring elements. Time complexity is .
Code Solution
median-two-arrays.ts
ts
1function findMedianSortedArrays(nums1: number[], nums2: number[]): number {2if (nums1.length > nums2.length) return findMedianSortedArrays(nums2, nums1);3const m = nums1.length, n = nums2.length;4let low = 0, high = m;5while (low <= high) {6const i = Math.floor((low + high) / 2);7const j = Math.floor((m + n + 1) / 2) - i;89const Aleft = i === 0 ? -Infinity : nums1[i - 1];10const Aright = i === m ? Infinity : nums1[i];11const Bleft = j === 0 ? -Infinity : nums2[j - 1];12const Bright = j === n ? Infinity : nums2[j];1314if (Aleft <= Bright && Bleft <= Aright) {15if ((m + n) % 2 === 0) {16return (Math.max(Aleft, Bleft) + Math.min(Aright, Bright)) / 2;17} else {18return Math.max(Aleft, Bleft);19}20} else if (Aleft > Bright) {21high = i - 1;22} else {23low = i + 1;24}25}26throw new Error('Input arrays not sorted or invalid');27}