Magnetic Force Between Two Balls (LeetCode 1552): Solution and Explanation
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
- Sort
position. - Set
lo = 1andhi = (position[n - 1] - position[0]) / (m - 1), the gap you would get by spreading the balls perfectly evenly. - While
lo < hi, take the upper middlemid = (lo + hi + 1) / 2so the range always shrinks. - Check
midgreedily: count balls placed when each one goes in the first basket at leastmidpast the last ball. Stop early oncemballs are placed. - If the check succeeds,
midis achievable, solo = mid. Otherwisehi = mid - 1. - Return
lo.
Step-by-step example
position = [1,2,3,4,7], m = 3
- Sorted already. lo = 1, hi = (7 - 1) / 2 = 3.
- mid = 2: balls at 1, then 3 (first basket at least 2 past 1), then 7. Three balls fit, so lo = 2.
- mid = 3: balls at 1, then 4, then 7. Three balls fit, so lo = 3.
- 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 lo1class Solution {
2 public int maxDistance(int[] position, int m) {
3 Arrays.sort(position);
4 int lo = 1, hi = (position[position.length - 1] - position[0]) / (m - 1);
5 while (lo < hi) {
6 int mid = lo + (hi - lo + 1) / 2;
7 if (canPlace(position, m, mid)) {
8 lo = mid;
9 } else {
10 hi = mid - 1;
11 }
12 }
13 return lo;
14 }
15
16 private boolean canPlace(int[] position, int m, int gap) {
17 int count = 1, last = position[0];
18 for (int i = 1; i < position.length; i++) {
19 if (position[i] - last >= gap) {
20 count++;
21 last = position[i];
22 if (count == m) {
23 return true;
24 }
25 }
26 }
27 return count >= m;
28 }
29}1class Solution {
2public:
3 int maxDistance(vector<int>& position, int m) {
4 sort(position.begin(), position.end());
5 int lo = 1, hi = (position.back() - position[0]) / (m - 1);
6 while (lo < hi) {
7 int mid = lo + (hi - lo + 1) / 2;
8 if (canPlace(position, m, mid)) {
9 lo = mid;
10 } else {
11 hi = mid - 1;
12 }
13 }
14 return lo;
15 }
16
17private:
18 bool canPlace(const vector<int>& position, int m, int gap) {
19 int count = 1, last = position[0];
20 for (size_t i = 1; i < position.size(); i++) {
21 if (position[i] - last >= gap) {
22 count++;
23 last = position[i];
24 if (count == m) {
25 return true;
26 }
27 }
28 }
29 return count >= m;
30 }
31};Time and space complexity
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).
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.