Advanced binary search
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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)); }}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,kas the number of days, and the allowed maximum subarray summidas the ship capacity! - If we cap each subarray sum at
mid, a greedy left-to-right scan counts the minimum number of subarrayspiecesneeded. Ifpieces <= k, thenmidis feasible (hi = mid); otherwiselo = mid + 1. lo = max(nums)(every element must fit into a subarray of capmid).hi = sum(nums)(1 single subarray holds everything).- Feasibility check: count greedy contiguous pieces with sum
<= mid; returnpieces <= 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.
- Sort
pos[]in ascending order. - Set
lo = 1,hi = (pos[n - 1] - pos[0]) / (k - 1). - Use the 'last true' binary search template (
mid = lo + (hi - lo + 1) / 2) withcanPlace(pos, k, mid).
Example 2 · Aggressive Cows — Maximize the Minimum Distance
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)); }}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?
- Always place the first cow in the leftmost stall
pos[0](placing it further right only leaves less room for the remaining cows). - Walk through the sorted stalls: place the next cow at the first stall
pos[i]wherepos[i] - lastPos >= dist. - If you place at least
kcows by the end of the array,distis feasible (lo = mid, try a larger distance); otherwisehi = 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
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})); }}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]) andmaxLeftB <= minRightA(B[j - 1] <= A[i]).- If
A[i - 1] > B[j], you took too many elements fromA(hi = i - 1); ifB[j - 1] > A[i], you took too few fromA(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.
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 resetTesting 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:
git bisect start,git bisect bad HEAD,git bisect good <old-sha>.- Git checks out the middle commit (
mid = 512). You run the test and typegit bisect goodorgit bisect bad. - In at most log₂(1,024) = 10 test runs (20 minutes instead of 34 hours!),
git bisectpinpoints the exact first broken commit—andgit bisect run ./test.shautomates the entire binary search hands-free!
Next step
Check your understanding
10 quick questions