Magnetic Force Between Two Balls — LeetCode 1552 Python Solution

MediumArrayBinary SearchSorting
Problem
#1552
Reading time
3 min

The 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 ith 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.

Example

Input
position = [1,2,3,4,7], m = 3
Output
3
Explanation
Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs [3, 3, 6]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.

Python solution

Python
class Solution:
    def maxDistance(self, position: List[int], m: int) -> int:
        def check(f: int) -> bool:
            prev = -inf
            cnt = 0
            for curr in position:
                if curr - prev >= f:
                    prev = curr
                    cnt += 1
            return cnt < m

        position.sort()
        l, r = 1, position[-1]
        return bisect_left(range(l, r + 1), True, key=check)

Complexity

MeasureComplexity
TimeO(n \times \log n + n \times \log M)
SpaceO(\log n) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 1552. Magnetic Force Between Two Balls is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1552. Magnetic Force Between Two Balls?
LeetCode 1552. Magnetic Force Between Two Balls is rated Medium on LeetCode.
What is the time complexity of LeetCode 1552. Magnetic Force Between Two Balls?
The Python solution on this page runs in O(n \times \log n + n \times \log M).
What is the space complexity of LeetCode 1552. Magnetic Force Between Two Balls?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 1552. Magnetic Force Between Two Balls cover?
LeetCode 1552. Magnetic Force Between Two Balls is tagged Array, Binary Search and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview