#1552

Magnetic Force Between Two Balls

Medium Binary search on the answer (aggressive cows)

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Place m balls into baskets at given positions so that the minimum distance between any two balls is as large as possible. Return that distance.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: place m balls to make the closest pair as far apart as possible ("aggressive cows").

Why this works: if a minimum gap d is possible, every smaller gap is too. Binary search d and place balls greedily from the left.

Example: positions [1, 2, 3, 4, 7], m = 3

d=3: place at 1, 4, 7 ✓d=4: place at 1, 7 only ✗ → answer 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Searching for the first feasible value (lower bound) when you need the last feasible one — use mid = (lo + hi + 1) / 2 with lo = mid.

Solve on LeetCode ↗
Complexity
  • Time: O(n log n + n log R).
  • Space: O(1) besides sorting.
Topic: Binary Search
🎬 Episodes 21–23: video coming soon