Skip to lesson

Advanced binary search

Two phrases in an interview problem almost always mean binary search on the answer: "minimize the maximum" (min-max) and "maximize the minimum" (max-min). Combined with the partition idea behind Median of Two Sorted Arrays and the real-world engineering tool git bisect, these patterns represent the pinnacle of binary search.

Split array largest sum

In Split Array Largest Sum (also known as Book Allocation or Painter's Partition), you are given an array of non-negative integers nums and an integer k.

Example 1 · Split Array Largest Sum — Minimize the Maximum

SplitArrayLargestSumDemo.javaJava
public class SplitArrayLargestSumDemo {    private static boolean canSplit(int[] nums, int k, long maxAllowedSum) {        int pieces = 1;        long currentSum = 0;        for (int x : nums) {            if (currentSum + x > maxAllowedSum) {                pieces++;                currentSum = x;            } else {                currentSum += x;            }        }        return pieces <= k;    }
    public static long splitArray(int[] nums, int k) {        long lo = 0, hi = 0;        for (int x : nums) {            lo = Math.max(lo, x);            hi += x;        }        while (lo < hi) {            long mid = lo + (hi - lo) / 2;            if (canSplit(nums, k, mid)) {                hi = mid;            } else {                lo = mid + 1;            }        }        return lo;    }
    public static void main(String[] args) {        int[] nums = {7, 2, 5, 10, 8};        System.out.println("Min largest sum (k=2): " + splitArray(nums, 2));        System.out.println("Min largest sum (k=3): " + splitArray(nums, 3));    }}
Output
Min largest sum (k=2): 18
Min largest sum (k=3): 14

What this code does

  • For k=2, splitting [7, 2, 5, 10, 8] into [7, 2, 5] (sum 14) and [10, 8] (sum 18) achieves a maximum sum of 18.
  • For k=3, splitting into [7, 2, 5] (14), [10] (10), and [8] (8) achieves a maximum sum of 14.

You must split nums into k non-empty contiguous subarrays so that the maximum subarray sum among the k pieces is as small as possible. Notice that this is the exact same problem as Capacity To Ship Packages Within D Days:

  • Think of each element nums[i] as a package weight, k as the number of days, and the allowed maximum subarray sum mid as the ship capacity!
  • If we cap each subarray sum at mid, a greedy left-to-right scan counts the minimum number of subarrays pieces needed. If pieces <= k, then mid is feasible (hi = mid); otherwise lo = mid + 1.
  • lo = max(nums) (every element must fit into a subarray of cap mid).
  • hi = sum(nums) (1 single subarray holds everything).
  • Feasibility check: count greedy contiguous pieces with sum <= mid; return pieces <= k.

Aggressive cows

Now consider the opposite twin—maximize the minimum: in Aggressive Cows (and Magnetic Force Between Two Balls), you have sorted stall positions pos[] along a barn and k cows.

  1. Sort pos[] in ascending order.
  2. Set lo = 1, hi = (pos[n - 1] - pos[0]) / (k - 1).
  3. Use the 'last true' binary search template (mid = lo + (hi - lo + 1) / 2) with canPlace(pos, k, mid).

Example 2 · Aggressive Cows — Maximize the Minimum Distance

AggressiveCowsDemo.javaJava
import java.util.Arrays;
public class AggressiveCowsDemo {    private static boolean canPlaceCows(int[] stalls, int cows, int minDist) {        int placed = 1;        int lastPos = stalls[0];        for (int i = 1; i < stalls.length; i++) {            if (stalls[i] - lastPos >= minDist) {                placed++;                lastPos = stalls[i];                if (placed == cows) return true;            }        }        return false;    }
    public static int maxMinDistance(int[] stalls, int cows) {        Arrays.sort(stalls);        int lo = 1;        int hi = (stalls[stalls.length - 1] - stalls[0]) / (cows - 1);        while (lo < hi) {            int mid = lo + (hi - lo + 1) / 2; // round up for last true!            if (canPlaceCows(stalls, cows, mid)) {                lo = mid;            } else {                hi = mid - 1;            }        }        return lo;    }
    public static void main(String[] args) {        int[] stalls = {1, 2, 8, 4, 9};        System.out.println("Max min distance for 3 cows: " + maxMinDistance(stalls, 3));    }}
Output
Max min distance for 3 cows: 3

What this code does

  • Sorted stalls are [1, 2, 4, 8, 9]. Placing cows at 1, 4, and 8 (or 9) gives minimum pairwise distance 3.
  • Trying minDist = 4 places cows at 1 and 8, leaving no room for a 3rd cow.

You want to place the k cows into stalls so that the minimum distance between any two cows is as large as possible. Suppose we guess a minimum required spacing dist = mid. How do we check if canPlace(pos, k, dist) is true?

  1. Always place the first cow in the leftmost stall pos[0] (placing it further right only leaves less room for the remaining cows).
  2. Walk through the sorted stalls: place the next cow at the first stall pos[i] where pos[i] - lastPos >= dist.
  3. If you place at least k cows by the end of the array, dist is feasible (lo = mid, try a larger distance); otherwise hi = mid - 1!

Median of two sorted arrays (idea)

Given two sorted arrays A (length m) and B (length n) with m ≤ n, how do you find the median of all m + n elements in O(log(min(m, n))) time without merging them?

Example 3 · Median of Two Sorted Arrays via binary search partition

MedianTwoSortedArraysDemo.javaJava
public class MedianTwoSortedArraysDemo {    public static double findMedianSortedArrays(int[] A, int[] B) {        if (A.length > B.length) return findMedianSortedArrays(B, A);        int m = A.length, n = B.length;        int half = (m + n + 1) / 2;        int lo = 0, hi = m;
        while (lo <= hi) {            int i = lo + (hi - lo) / 2;            int j = half - i;
            int maxLeftA = (i == 0) ? Integer.MIN_VALUE : A[i - 1];            int minRightA = (i == m) ? Integer.MAX_VALUE : A[i];            int maxLeftB = (j == 0) ? Integer.MIN_VALUE : B[j - 1];            int minRightB = (j == n) ? Integer.MAX_VALUE : B[j];
            if (maxLeftA <= minRightB && maxLeftB <= minRightA) {                int maxLeft = Math.max(maxLeftA, maxLeftB);                if ((m + n) % 2 == 1) return maxLeft;                int minRight = Math.min(minRightA, minRightB);                return (maxLeft + minRight) / 2.0;            } else if (maxLeftA > minRightB) {                hi = i - 1;            } else {                lo = i + 1;            }        }        throw new IllegalArgumentException();    }
    public static void main(String[] args) {        System.out.println(findMedianSortedArrays(new int[]{1, 3}, new int[]{2}));        System.out.println(findMedianSortedArrays(new int[]{1, 2}, new int[]{3, 4}));    }}
Output
2.0
2.5

What this code does

  • By always binary searching on the shorter array A (length m <= n), j = half - i is guaranteed to stay within [0 .. n].
  • Sentinel values Integer.MIN_VALUE and Integer.MAX_VALUE cleanly handle empty left or right partitions at i = 0 or i = m.
  • maxLeftA <= minRightB (A[i - 1] <= B[j]) and maxLeftB <= minRightA (B[j - 1] <= A[i]).
  • If A[i - 1] > B[j], you took too many elements from A (hi = i - 1); if B[j - 1] > A[i], you took too few from A (lo = i + 1).

Finding the median means partitioning the combined elements into a left half of size half = (m + n + 1) / 2 and a right half of size (m + n) - half such that every element in the left half is <= every element in the right half. If you take i elements from A (A[0 .. i - 1]) for the left half, you must take the remaining j = half - i elements from B (B[0 .. j - 1])! So i and j are locked together—you only need to binary search i in [0 .. m] until the cross-boundary condition holds:

Real world: git bisect finds the commit that broke a build

git bisect is Git's built-in binary search: it finds the first commit that broke a build. Imagine your team's test suite passed 1,024 commits ago (good), fails on HEAD today (bad), and running the integration test suite takes 2 minutes.

Terminal
git bisect startgit bisect bad HEADgit bisect good a1b2c3d# Git checks out the middle commit. Run the test, then answer:git bisect good# ...or: git bisect bad. Repeat until Git names the first bad commit.git bisect run ./test.shgit bisect reset

Testing all 1,024 commits linearly would take 2,048 minutes (34 hours)!

Because a bug introduced at commit C stays broken in subsequent commits (a monotonic [good, good, ..., good, bad, bad, ..., bad] history), Git's built-in git bisect command runs lowerBound across the commit graph:

  1. git bisect start, git bisect bad HEAD, git bisect good <old-sha>.
  2. Git checks out the middle commit (mid = 512). You run the test and type git bisect good or git bisect bad.
  3. In at most log₂(1,024) = 10 test runs (20 minutes instead of 34 hours!), git bisect pinpoints the exact first broken commit—and git bisect run ./test.sh automates the entire binary search hands-free!

Next step

Check your understanding

10 quick questions