In the Magnetic Force Between Two Balls problem, you are given an array of positions representing empty baskets along a line, and an integer m representing the number of magnetic balls. You need to place all m balls into the baskets such that the minimum magnetic force between any two balls is maximized. The force between a ball at position x and y is simply |x - y|.
This is a textbook "Minimize the Maximum" or "Maximize the Minimum" optimization problem. It is a favorite among top-tier tech companies because it tests your ability to recognize when to apply Binary Search on the Answer. It forces you to transition from asking "How do I place these balls optimally?" to "If I guess a specific force, can I successfully place all the balls?"
The absolute optimal pattern here is Binary Search on the Answer. First, sort the position array. Then, define a search space for the possible minimum force: from 1 (balls in adjacent baskets) to max_position - min_position (balls at extreme ends). For a guessed mid-point force F, use a Greedy approach to see if you can place all m balls such that every pair is at least F distance apart. If you can, search higher; if you can't, search lower.
Positions: [1, 2, 3, 4, 7], m = 3 balls.
Sorted positions: [1, 2, 3, 4, 7].
Let's binary search the force. Max possible force is . Midpoint force .
Can we place 3 balls with at least 3 distance?
1.4 is valid. Ball 2 goes at 4.7 is valid. Ball 3 goes at 7.
We successfully placed all 3 balls with a minimum distance of 3! We can now try to search for an even larger force (e.g., 4). It will fail, leaving 3 as our maximum possible minimum force.A very common mistake is trying to solve this using Dynamic Programming, which is overly complex and usually results in a Time Limit Exceeded error. Another mistake is forgetting to sort the array of basket positions initially. The greedy placement logic strictly requires the baskets to be evaluated in ascending order to simulate walking down the physical line.
When tackling the Magnetic Force Between Two Balls coding problem, internalize the phrasing "maximize the minimum." This phrase is a massive neon sign pointing to Binary Search. Practice writing the greedy canPlace(m, force) helper function; it is incredibly simple (just loop and check if current_position - last_placed_position >= force) and forms the core of many similar problems like 'Allocate Books' or 'Koko Eating Bananas'.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find Right Interval | Medium | Solve | |
| Most Beautiful Item for Each Query | Medium | Solve | |
| Sum of Mutated Array Closest to Target | Medium | Solve | |
| Special Array With X Elements Greater Than or Equal X | Easy | Solve | |
| Find Target Indices After Sorting Array | Easy | Solve |