Visualize

Pattern visualizer

Aggressive Cows

Nothing in the stall list is the answer, so there is no cell to search for. Turn it around and ask a yes/no question instead: can the cows be seated with every pair at least d apart? A left-to-right greedy answers that in one pass, and the answers are monotonic — if d works, every smaller gap works, and once d fails every larger gap fails too. That yes/no flip is exactly the sorted-true-then-false shape binary search needs, so we search d itself and keep the largest d that still answers yes. Animated on: stalls = 29, 1, 41, 20, 58, 12, 70, 5 and k = 4 cows — seat one cow per stall so that the smallest distance between any two cows is as large as possible..

Binary search the ANSWER, then greedily test it

time O(n log n + n log(max - min))space O(1)step 1 / 10
29
[0]
1
[1]
41
[2]
20
[3]
58
[4]
12
[5]
70
[6]
5
[7]
line 1

8 stalls at 29, 1, 41, 20, 58, 12, 70, 5 and 4 cows to seat. The cows fight, so we want the placement where the CLOSEST pair of cows is as far apart as possible.

Pseudocode
1FUNCTION maxMinDistance(stalls, k):
2 stalls <- SORT(stalls)
3 low <- 1
4 high <- stalls[LENGTH(stalls) - 1] - stalls[0]
5 WHILE low <= high
6 mid <- (low + high) / 2
7 IF canPlace(stalls, k, mid)
8 best <- mid
9 low <- mid + 1
10 ELSE
11 high <- mid - 1
12 RETURN best

← / → step · space play · Home restart

Where to practice Binary Search