An interactive visualization of finding the median of two sorted arrays using binary search on the partition point. Watch the algorithm achieve O(log(min(m,n))) time complexity by partitioning the smaller array.
Binary Search LeetCode 4 ↗ Hardnums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.O(log(min(m,n))).fun findMedianSortedArrays(nums1: IntArray, nums2: IntArray): Double { var a = nums1; var b = nums2 if (a.size > b.size) { a = nums2; b = nums1 } val m = a.size; val n = b.size var lo = 0; var hi = m while (lo <= hi) { val i = (lo + hi) / 2 val j = (m + n + 1) / 2 - i val maxLeftA = if (i == 0) Int.MIN_VALUE else a[i - 1] val minRightA = if (i == m) Int.MAX_VALUE else a[i] val maxLeftB = if (j == 0) Int.MIN_VALUE else b[j - 1] val minRightB = if (j == n) Int.MAX_VALUE else b[j] if (maxLeftA <= minRightB && maxLeftB <= minRightA) { if ((m + n) % 2 == 1) return maxOf(maxLeftA, maxLeftB).toDouble() return (maxOf(maxLeftA, maxLeftB) + minOf(minRightA, minRightB)) / 2.0 } else if (maxLeftA > minRightB) { hi = i - 1 } else { lo = i + 1 } } return 0.0}
Instead of merging the arrays, we use binary search on the partition point of the shorter array. The key idea: if we partition both arrays such that all elements on the left are ≤ all elements on the right, and both halves have equal size (or left has one more), then the median is determined by the boundary elements.
lo = 0, hi = len(A)i in A, compute j = (m+n+1)//2 - i in BmaxLeftA, minRightA, maxLeftB, minRightB (use -∞ and +∞ for empty partitions)maxLeftA ≤ minRightB AND maxLeftB ≤ minRightA, partition is correctmax(maxLeftA, maxLeftB); if even, return average of max(maxLeftA, maxLeftB) and min(minRightA, minRightB)maxLeftA > minRightB, move left (hi = i - 1); otherwise move right (lo = i + 1)
Binary search is performed on the shorter array only, giving O(log(min(m,n))) time complexity.
Only a constant number of variables are used regardless of input size.