Magnetic Force Between Two Balls (LeetCode 1552): Solution and Explanation

Medium
Array
Binary Search
Sorting

Place m balls in distinct baskets on a line so that the smallest distance between any two balls is as large as possible, and return that distance.

Intuition

Asking for the best placement directly is hard. Asking a yes or no question is easy: can all m balls fit with every neighbouring pair at least d apart?

That question has a monotone answer. If gap d works, every smaller gap works with the same placement, and if d fails, every larger gap fails too. So the answers look like yes, yes, ..., yes, no, no, and binary search can find the last yes.

To answer one question, sort the baskets and place balls greedily. Put the first ball in the leftmost basket and each next ball in the first basket at least d past the previous one. Placing a ball as early as possible never hurts, because it leaves the most room for the balls after it.

Approach: Binary search on the answer + greedy placement

  1. Sort position.
  2. Set lo = 1 and hi = (position[n - 1] - position[0]) / (m - 1), the gap you would get by spreading the balls perfectly evenly.
  3. While lo < hi, take the upper middle mid = (lo + hi + 1) / 2 so the range always shrinks.
  4. Check mid greedily: count balls placed when each one goes in the first basket at least mid past the last ball. Stop early once m balls are placed.
  5. If the check succeeds, mid is achievable, so lo = mid. Otherwise hi = mid - 1.
  6. Return lo.

Step-by-step example

position = [1,2,3,4,7], m = 3
  1. Sorted already. lo = 1, hi = (7 - 1) / 2 = 3.
  2. mid = 2: balls at 1, then 3 (first basket at least 2 past 1), then 7. Three balls fit, so lo = 2.
  3. mid = 3: balls at 1, then 4, then 7. Three balls fit, so lo = 3.
  4. lo = hi = 3, so the answer is 3.

Code: Python, Java, C++

1class Solution:
2    def maxDistance(self, position: List[int], m: int) -> int:
3        position.sort()
4
5        def can_place(gap: int) -> bool:
6            count, last = 1, position[0]
7            for p in position[1:]:
8                if p - last >= gap:
9                    count += 1
10                    last = p
11                    if count == m:
12                        return True
13            return count >= m
14
15        lo, hi = 1, (position[-1] - position[0]) // (m - 1)
16        while lo < hi:
17            mid = (lo + hi + 1) // 2
18            if can_place(mid):
19                lo = mid
20            else:
21                hi = mid - 1
22        return lo
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log n + n log R)

Sorting costs O(n log n). The binary search runs O(log R) rounds, where R is the distance between the outer baskets (up to 10^9, about 30 rounds), and each greedy check is O(n).

Space

O(1)

Apart from the sort's own stack space, only a few counters are kept.

Other approaches

Linear scan over every gap (time O(n R), space O(1))

Try every gap from hi down to 1 and return the first that passes the greedy check. Correct, but R can be 10^9, so it is far too slow.

Binary search with lower middle (time O(n log n + n log R), space O(1))

Search for the first gap that fails instead, using lo = mid + 1 on success and returning lo - 1. Equivalent, just a different loop invariant.

Common mistakes

  • Using mid = (lo + hi) / 2 together with lo = mid. When hi = lo + 1 the loop never shrinks and runs forever. Round up when the success branch keeps mid.
  • Forgetting to sort. The greedy check relies on scanning baskets from left to right.
  • Setting hi to max - min instead of (max - min) / (m - 1). Both are correct upper bounds, but the tighter one saves a few rounds.
  • Placing the first ball anywhere other than the leftmost basket. Starting later can only reduce the room for the remaining balls.

Frequently asked questions

Why does the greedy check give the right yes or no answer?

Take any valid placement for gap d. Moving its first ball to the leftmost basket keeps every gap at least d, and then each later ball can slide left to the greedy choice without breaking a gap. So if any placement exists, the greedy one places at least m balls.

Is this the same as the aggressive cows problem?

Yes. Cows in stalls and balls in baskets are the same task: maximize the minimum distance between chosen points on a line, solved by binary searching the distance.

Can the answer overflow a 32-bit integer?

No. Positions are at most 10^9, so every gap and the search bounds stay below 2^31.