Binary Search · Pattern 8 of 8
Binary search on a partition
Split two sorted arrays so the left parts hold exactly half the elements and everything on the left is ≤ everything on the right. Binary search where to cut the shorter array.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Median or kth element of two sorted arrays
- The expected time is O(log(min(m, n)))
The template
double findMedianSortedArrays(int[] a, int[] b) {
if (a.length > b.length) return findMedianSortedArrays(b, a); // cut the shorter one
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; // i from a and j from b go left
int aL = i == 0 ? Integer.MIN_VALUE : a[i - 1], aR = i == m ? Integer.MAX_VALUE : a[i];
int bL = j == 0 ? Integer.MIN_VALUE : b[j - 1], bR = j == n ? Integer.MAX_VALUE : b[j];
if (aL <= bR && bL <= aR) { // a valid split
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; // took too many from a
else lo = i + 1; // took too few from a
}
throw new IllegalArgumentException("inputs are not sorted");
} def find_median_sorted_arrays(a, b):
if len(a) > len(b):
a, b = b, a # cut the shorter one
m, n = len(a), len(b)
half = (m + n + 1) // 2
lo, hi = 0, m
while lo <= hi:
i = (lo + hi) // 2 # i from a and j from b go left
j = half - i
a_l = a[i - 1] if i > 0 else float('-inf')
a_r = a[i] if i < m else float('inf')
b_l = b[j - 1] if j > 0 else float('-inf')
b_r = b[j] if j < n else float('inf')
if a_l <= b_r and b_l <= a_r: # a valid split
if (m + n) % 2:
return max(a_l, b_l)
return (max(a_l, b_l) + min(a_r, b_r)) / 2
if a_l > b_r:
hi = i - 1 # took too many from a
else:
lo = i + 1 # took too few from a
raise ValueError("inputs are not sorted") double findMedianSortedArrays(vector<int>& a, vector<int>& b) {
if (a.size() > b.size()) return findMedianSortedArrays(b, a); // cut the shorter one
int m = a.size(), n = b.size(), half = (m + n + 1) / 2;
int lo = 0, hi = m;
while (lo <= hi) {
int i = (lo + hi) / 2, j = half - i; // i from a and j from b go left
int aL = i == 0 ? INT_MIN : a[i - 1], aR = i == m ? INT_MAX : a[i];
int bL = j == 0 ? INT_MIN : b[j - 1], bR = j == n ? INT_MAX : b[j];
if (aL <= bR && bL <= aR) { // a valid split
if ((m + n) % 2 == 1) return max(aL, bL);
return (max(aL, bL) + (double)min(aR, bR)) / 2;
}
if (aL > bR) hi = i - 1; // took too many from a
else lo = i + 1; // took too few from a
}
throw invalid_argument("inputs are not sorted");
} function findMedianSortedArrays(a, b) {
if (a.length > b.length) [a, b] = [b, a]; // cut the shorter one
const m = a.length, n = b.length, half = (m + n + 1) >> 1;
let lo = 0, hi = m;
while (lo <= hi) {
const i = (lo + hi) >> 1, j = half - i; // i from a and j from b go left
const aL = i === 0 ? -Infinity : a[i - 1], aR = i === m ? Infinity : a[i];
const bL = j === 0 ? -Infinity : b[j - 1], bR = j === n ? Infinity : b[j];
if (aL <= bR && bL <= aR) { // a valid split
if ((m + n) % 2 === 1) return Math.max(aL, bL);
return (Math.max(aL, bL) + Math.min(aR, bR)) / 2;
}
if (aL > bR) hi = i - 1; // took too many from a
else lo = i + 1; // took too few from a
}
throw new Error('inputs are not sorted');
} The variations
-
1Partition two sorted arrays
Take i elements from a and half − i from b for the left side. The split is right when a's left max ≤ b's right min and b's left max ≤ a's right min. Otherwise move i.
Mistakes to avoid
- Binary searching the longer array: j can go negative. Always cut the shorter one.
- Forgetting the sentinels (−∞ / +∞) when a side of the cut is empty.
Lesson done
Back to Binary Search →Mark it done once you can write the template from memory and you have solved the worked examples yourself.