Magnetic Force Between Two Balls

Medium

Topics
ArrayBinary SearchSorting

Given an array nums of distinct basket positions and an integer target (= m balls), place the balls into baskets so that the minimum distance between any two balls is as large as possible. Return that maximum possible minimum distance.

Example 1

1021324374
baskets used
The largest workable gap is 3.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [1,2,3,4,7], target = 3
Output: 3

Example 2

504132231410000000005
baskets used
Input:  nums = [5,4,3,2,1,1000000000], target = 2
Output: 999999999

Constraints

  • 2 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^9
  • All positions are distinct.
  • 2 <= target <= nums.length
Editorial — intuition, approach, complexity and pitfalls

Intuition

We place m balls in given positions so that the minimum gap between any two is as large as possible. Choosing which positions to use directly is combinatorial; the way in is to search the answer instead.

Guess a minimum gap d and ask the easier question: can we place m balls with every pair at least d apart? Greedily — sort the positions, take the first, then take each next position that is at least d beyond the last one taken. Taking the earliest feasible position always leaves the most room behind it, so this maximises how many balls fit.

The count of placeable balls is non-increasing in d, which is the monotonicity binary search needs. So search d over [1, max - min] and keep the largest feasible value.

💡 Same shape as "divide chocolate" and "ship packages within D days": binary search on the answer with a linear greedy feasibility check. The giveaway is "maximise the minimum".

Approach

  1. Sort the positions — the greedy requires order.
  2. Binary search d over [1, max - min].
  3. For each d, greedily count placeable balls; if it reaches m, record d and try larger.

Dry Run

position = [1,2,3,4,7], m = 3
sorted [1,2,3,4,7],  lo=1 hi=6

mid=3  place 1, next >= 4 -> 4, next >= 7 -> 7   3 balls  feasible, ans=3, lo=4
mid=5  place 1, next >= 6 -> 7                   2 balls  short,     hi=4
mid=4  place 1, next >= 5 -> 7                   2 balls  short,     hi=3
lo > hi

answer 3   (balls at 1, 4, 7 -- minimum gap 3)

Complexity

  • Time — O(n log(max)): the sort is O(n log n) and each of about 30 probes is a linear pass.
  • Space — O(log n) in Java and C++, O(n) in Python, all of it the sort. The greedy check holds two counters — and note it must iterate by index rather than slicing positions[1:], which would copy the array on every probe.

Common Pitfalls

  • Forgetting to sort. The greedy depends entirely on ascending order.
  • Slicing inside the feasibility check. It runs once per probe, so an O(n) copy there is paid thirty times over.
  • Using > instead of >= for the gap test, which rejects a placement that exactly meets the target.
  • Starting lo at 0. A gap of 0 is always feasible and wastes a probe; worse, it muddies the invariant that every candidate is a real distance.
  • Binary searching the number of balls rather than the gap. The ball count is the constraint; the gap is the unknown.

Full Solution — all languages

class Solution:
    def maxDistance(self, nums, target):
        nums.sort()
        n = len(nums)

        def ok(d):
            # Index loop, not `for p in nums[1:]`: that slice copies the array on
            # every binary-search probe, which is both O(n) space and O(n) wasted
            # copying per iteration.
            cnt, last = 1, nums[0]
            for i in range(1, n):
                if nums[i] - last >= d:
                    cnt += 1
                    last = nums[i]
            return cnt

        lo, hi, ans = 1, nums[-1] - nums[0], 0
        while lo <= hi:
            mid = lo + (hi - lo) // 2
            if ok(mid) >= target:
                ans = mid
                lo = mid + 1
            else:
                hi = mid - 1
        return ans
Asked at Roblox
SensAI
Beta
Tap the mic to stop voice mode