Magnetic Force Between Two Balls - Problem

In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has n empty baskets, the i-th basket is at position[i]. Morty has m balls and needs to distribute the balls into the baskets such that the minimum magnetic force between any two balls is maximum.

Rick stated that magnetic force between two different balls at positions x and y is |x - y|.

Given the integer array position and the integer m. Return the required force.

Input & Output

Example 1 — Basic Case
$ Input: position = [1,2,3,4,7], m = 3
Output: 3
💡 Note: Place balls at positions 1, 4, and 7. The minimum distance between any two balls is min(|4-1|, |7-4|, |7-1|) = min(3, 3, 6) = 3.
Example 2 — Closer Positions
$ Input: position = [5,4,3,2,1,1000000000], m = 2
Output: 999999999
💡 Note: Place balls at positions 1 and 1000000000. The distance between them is |1000000000 - 1| = 999999999, which is the maximum possible minimum distance.
Example 3 — All Balls Must Fit
$ Input: position = [1,2,8,4,9], m = 4
Output: 1
💡 Note: After sorting positions = [1,2,4,8,9]. To place 4 balls, we can place them at positions 1, 2, 4, 8 with minimum distance = 1.

Constraints

  • 2 ≤ n ≤ 105
  • 1 ≤ m ≤ n
  • 1 ≤ position[i] ≤ 109
  • All position[i] are distinct

Visualization

Tap to expand
Magnetic Force Between Two Balls INPUT Basket Positions on Number Line 1 2 3 4 7 5 baskets at positions above position = [1,2,3,4,7] m = 3 (balls to place) n = 5 (baskets) Goal: Maximize minimum distance between balls Force = |x - y| (distance) Binary search on force value ALGORITHM (Greedy) 1 Sort positions [1,2,3,4,7] (already sorted) 2 Binary search range low=1, high=(7-1)/(3-1)=3 3 Check feasibility Greedy: place balls with min distance = mid 4 Binary search iteration If can place --> try larger Else --> try smaller Binary Search Trace mid=2: [1,3,7] OK, 3 balls mid=3: [1,4,7] OK, 3 balls mid=4: [1,7] FAIL, 2 balls Answer: 3 Balls at: 1, 4, 7 FINAL RESULT Optimal Ball Placement 1 2 3 4 7 B1 B2 B3 |4-1| = 3 |7-4| = 3 Output: 3 Maximum min force [OK] Solution Verified Balls at positions: 1, 4, 7 Min distance = 3 Cannot achieve force > 3 Key Insight: Binary search on the answer! Instead of searching positions, search for the minimum force value. For each candidate force, use greedy placement: place each ball at the earliest valid position. Time: O(n log n + n log(max_pos)) | Space: O(1) for the greedy check TutorialsPoint - Magnetic Force Between Two Balls | Greedy + Binary Search Approach
Asked in
Google 15 Amazon 12 Microsoft 8
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen