Magnetic Force Between Two Balls, solved by searching the answer
Magnetic Force Between Two Balls is a maximize-the-minimum problem: sort the positions, then binary search on the smallest allowed gap and test each guess greedily by dropping a ball in the first position and every next position at least that far away. The largest gap that fits all the balls is the answer, in O(n log n + n log D) time where D is the span of the positions.
By Evin JohnPublished 8 min read
The setup
There are n baskets standing at distinct integer positions along a line, given in no particular order. You must place m balls, at most one per basket, with m at least 2 and at most n. The force between two balls is the distance between their baskets, and the weakest link is the smallest such distance among all pairs. Choose baskets so the weakest link is as large as possible, and return that value. The same problem is often told as placing cows in stalls or routers along a street.
| Positions | Balls | Best minimum gap | One optimal choice |
|---|---|---|---|
| [2, 9, 5, 14, 11] | 3 | 5 | 2, 9, 14 |
| [1, 100] | 2 | 99 | 1, 100 |
| [3, 4, 5, 6] | 4 | 1 | All four baskets |
| [10, 1, 7, 4] | 3 | 3 | 1, 4, 7 |
Before coding, confirm that positions are distinct and that m never exceeds n. Also ask about the size of the coordinates: if they can reach a billion, the search range is large but the binary search handles it in about thirty steps.
Slow route: test gaps one by one
Checking every subset of m baskets would be correct but exponential. A smarter slow method fixes the gap first. For a gap g, can you place all m balls so that neighbors are at least g apart? Walk the sorted positions, place a ball at the first basket, and place the next ball at the first basket at least g beyond the last one. If you place m balls, g works. Try g = 1, 2, 3 and so on until it fails. That costs O(n) per gap and up to D gaps, where D is the distance from the first to the last basket.
def max_min_gap_scan(spots, balls):
spots = sorted(spots)
best = 0
for gap in range(1, spots[-1] - spots[0] + 1):
placed, last = 1, spots[0]
for p in spots[1:]:
if p - last >= gap:
placed += 1
last = p
if placed < balls:
break
best = gap
return bestWhy greedy placement is enough
Suppose some arrangement achieves gap g. Compare it with the greedy one ball by ball. The greedy first ball is at the leftmost basket, no later than the other arrangement's first ball. If the greedy ball number t is no later than the other ball number t, then the next basket at least g past the greedy ball is no later than the other arrangement's ball t + 1. By induction the greedy run is always at or behind the other one, so it places at least as many balls. If any arrangement fits m balls with gap g, the greedy one does too.
Binary search on the answer
Feasibility is monotone. If gap g works, any smaller gap works with the same placement. So the gaps split into a run of yes answers followed by a run of no answers, and you want the last yes. Binary search the gap between 1 and the span divided by m - 1, which is the largest gap that could possibly fit: m balls create m - 1 gaps that together cannot exceed the span.
Because you want the largest feasible value, round the midpoint up. With lo = mid on success, rounding down could leave lo and hi one apart forever.
def max_min_gap(spots, balls):
spots = sorted(spots)
def fits(gap):
placed, last = 1, spots[0]
for p in spots[1:]:
if p - last >= gap:
placed += 1
last = p
if placed == balls:
return True
return placed >= balls
lo, hi = 1, (spots[-1] - spots[0]) // (balls - 1)
while lo < hi:
mid = (lo + hi + 1) // 2
if fits(mid):
lo = mid
else:
hi = mid - 1
return lofunction maxMinGap(spots, balls) {
const pos = [...spots].sort((a, b) => a - b);
const fits = (gap) => {
let placed = 1;
let last = pos[0];
for (let i = 1; i < pos.length; i++) {
if (pos[i] - last >= gap) {
placed++;
last = pos[i];
if (placed === balls) return true;
}
}
return placed >= balls;
};
let lo = 1;
let hi = Math.floor((pos[pos.length - 1] - pos[0]) / (balls - 1));
while (lo < hi) {
const mid = Math.floor((lo + hi + 1) / 2);
if (fits(mid)) lo = mid;
else hi = mid - 1;
}
return lo;
}Why is 1 always a safe lower bound? Positions are distinct integers, so any two baskets are at least 1 apart, and placing balls in the first m baskets always achieves a gap of at least 1.
Tracing the first example
Sorted positions are 2, 5, 9, 11, 14 and m is 3. The span is 12, so hi starts at 12 // 2 = 6 and lo at 1. The midpoint, rounded up, is 4: the greedy run places balls at 2, 9 and 14, so 4 fits and lo becomes 4. Next midpoint is 5: balls at 2, 9 and 14 again, gaps 7 and 5, so 5 fits and lo becomes 5. Next midpoint is 6: balls at 2 and 9, then nothing at 15 or beyond, so it fails and hi becomes 5. lo equals hi, and the answer is 5.
Time and space
| Strategy | Time | Memory |
|---|---|---|
| Every subset of m baskets | O(C(n, m) times m) | O(m) |
| Every gap with greedy check | O(n log n + n D) | O(n) for the sorted copy |
| Binary search on gap with greedy check | O(n log n + n log D) | O(n) for the sorted copy |
Sorting dominates when the coordinates are small. When they are large, the n log D term takes over, but log D stays near 30 for coordinates up to a billion. Sorting in place drops the memory to whatever the sort itself uses, if mutating the input is acceptable.
Edge cases
- Two balls: the answer is simply the last position minus the first, and hi starts exactly there.
- As many balls as baskets: every basket is used, so the answer is the smallest gap between neighbors.
- Unsorted input. Forgetting to sort makes the greedy check meaningless.
- Clustered positions with one far outlier, like [1, 2, 3, 1000] with 3 balls. The greedy check picks 1, then a middle basket, then 1000, and the answer is 2.
Typical mistakes
- Rounding the midpoint down while using `lo = mid`. The loop stalls when lo and hi differ by one.
- Using JavaScript's default sort. Without a comparator,
[10, 9, 100].sort()sorts as strings and gives [10, 100, 9]. - Counting balls from 0. The first ball goes into the first basket, so the counter starts at 1.
- Searching from 0. A gap of 0 is trivially feasible and can hide off-by-one bugs; start at 1.
- Trying to pick spread-out baskets by dividing the span evenly. Positions are fixed, so an even split may land between baskets. The greedy check is what makes the answer exact.
Sample narration
Fictional example
- Candidate
- We want to maximize a minimum, which usually means guessing the answer and checking it. Given a gap, I can sort the baskets and place balls greedily from the left, always at the earliest basket that keeps the gap.
- Candidate
- If a gap works, every smaller gap works, so I can binary search for the largest one. The search range is 1 to the span divided by m minus 1.
- Candidate
- Each check is linear, so it is n log n to sort plus n log of the span to search. I will round the midpoint up because I move lo to mid on success.
More from this set
Minimize Max Distance to Gas Station flips the goal to minimizing a maximum and searches over real numbers instead of integers. Kth Smallest Number in Multiplication Table also searches an answer range, with a count as the test. If you want an index-based warm-up first, try Search in Rotated Sorted Array II. The algorithm interview questions page has more on greedy reasoning.
Practice support from Natively
If your practice problems live in screenshots, Natively can read one and suggest an approach, which makes a useful comparison after you have worked it through yourself. It can also produce a transcript of a mock round on your computer, so you can confirm you explained why the greedy check is safe. The AI interview assistant page has the details.
Questions people ask
How do you solve Magnetic Force Between Two Balls?
Sort the positions and binary search on the minimum gap. For each guess, place balls greedily from the left at the first basket that keeps the gap; if all balls fit, try a larger gap, otherwise a smaller one.
Why does the greedy placement work?
Placing each ball at the earliest legal basket never falls behind any other valid arrangement, so if some placement fits all the balls with a given gap, the greedy one does too.
What is the time complexity?
O(n log n) to sort plus O(n log D) for the search, where D is the distance between the first and last basket. Extra memory is the sorted copy, or none beyond the sort if you sort in place.
Is this the same as the aggressive cows problem?
It is the same pattern: maximize the minimum distance between chosen points on a line. The story differs, but the binary search on the answer with a greedy check is identical.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
