#1552

Magnetic Force Between Two Balls

Medium
ArrayBinary SearchSortingBinary SearchGreedy Algorithm
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log(max_distance))
Space
O(1)
O(1)
💡

Intuition

Time O(n log(max_distance))Space O(1)

The optimal solution uses binary search to find the maximum minimum magnetic force. By checking if a certain force can be achieved, we can efficiently narrow down the possible values.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the positions array.
  2. 2Step 2: Use binary search on the possible minimum forces (from 1 to max(position) - min(position)).
  3. 3Step 3: For each mid value in binary search, check if it's possible to place m balls with at least mid distance apart using a greedy approach.
solution.py24 lines
1# Full working Python code
2def canPlaceBalls(position, m, min_force):
3    count = 1
4    last_position = position[0]
5    for i in range(1, len(position)):
6        if position[i] - last_position >= min_force:
7            count += 1
8            last_position = position[i]
9            if count == m:
10                return True
11    return False
12
13def maxMinForce(position, m):
14    position.sort()
15    left, right = 1, position[-1] - position[0]
16    result = 0
17    while left <= right:
18        mid = (left + right) // 2
19        if canPlaceBalls(position, m, mid):
20            result = mid
21            left = mid + 1
22        else:
23            right = mid - 1
24    return result

Complexity note: The time complexity is O(n log(max_distance)) because we perform a binary search on the distance (which can be at most the difference between the max and min positions) and for each mid value, we check if we can place the balls in O(n) time.

  • 1Sorting the positions helps in easily calculating distances.
  • 2Binary search allows us to efficiently find the maximum minimum force.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.