The Aggressive Cows problem is a classic example where we want to use binary search on the answer. Instead of searching through positions, we ask: what is the largest possible minimum distance we can achieve between cows placed in stalls?
Understanding the Problem
We are given stall positions — say [1, 2, 4, 8, 9]
— and asked to place K
cows in them. The twist is: we want to maximize the minimum distance between any two cows. That means, the cows should be as far apart as possible, but we still need to fit all of them into the stalls.
Different Scenarios to Consider
- Exact fit: If the number of cows equals the number of stalls, the only option is one cow per stall, and the smallest distance between any two is what we return.
- Single cow: If there’s only one cow to place, we can put it anywhere. There’s no pair to measure distance, so the answer is
0
.
- Too many cows: If
K > N
, we cannot place all cows — so we return -1
or some invalid flag.
- Empty stalls: If the stall list is empty, there’s no way to place any cows — again, return
-1
.
How the Strategy Works
First, we sort the stall positions to ensure they're in order. Then, we try to guess the minimum distance between cows (starting from 1 up to the max difference between stalls) using binary search.
At each step, we check: "Can we place all K
cows such that the gap between any two is at least mid
?"
- If yes → maybe we can do even better, so try a bigger distance.
- If no → that distance is too much, reduce the range.
We keep narrowing the range until we find the largest distance that works — that’s our answer.
Efficiency
This method is very efficient: we’re doing a binary search on distance (which ranges from 1 to max stall gap), and for each guess, we do a linear pass to see if placement is possible. This gives us an overall time complexity of O(N log(MaxDistance)).
It’s an excellent real-world inspired problem that blends greedy thinking with binary search — ideal for learning how to "search on the answer".