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.

1 variation · 1 problem

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

Binary Search on Partition
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");
}

The variations

  1. 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.
Back to Binary Search →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.