Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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.
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.
Example 1:
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.
Example 2:
Input: position = [5,4,3,2,1,1000000000], m = 2 Output: 999999999 Explanation: We can use baskets 1 and 1000000000.
Constraints:
n == position.length2 <= n <= 1051 <= position[i] <= 109position are distinct.2 <= m <= position.lengthProblem summary: 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. 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search
[1,2,3,4,7] 3
[5,4,3,2,1,1000000000] 2
minimized-maximum-of-products-distributed-to-any-store)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1552: Magnetic Force Between Two Balls
class Solution {
private int[] position;
public int maxDistance(int[] position, int m) {
Arrays.sort(position);
this.position = position;
int l = 1, r = position[position.length - 1];
while (l < r) {
int mid = (l + r + 1) >> 1;
if (count(mid) >= m) {
l = mid;
} else {
r = mid - 1;
}
}
return l;
}
private int count(int f) {
int prev = position[0];
int cnt = 1;
for (int curr : position) {
if (curr - prev >= f) {
++cnt;
prev = curr;
}
}
return cnt;
}
}
// Accepted solution for LeetCode #1552: Magnetic Force Between Two Balls
func maxDistance(position []int, m int) int {
sort.Ints(position)
return sort.Search(position[len(position)-1], func(f int) bool {
prev := position[0]
cnt := 1
for _, curr := range position {
if curr-prev >= f {
cnt++
prev = curr
}
}
return cnt < m
}) - 1
}
# Accepted solution for LeetCode #1552: Magnetic Force Between Two Balls
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)
// Accepted solution for LeetCode #1552: Magnetic Force Between Two Balls
struct Solution;
impl Solution {
fn max_distance(mut position: Vec<i32>, m: i32) -> i32 {
position.sort_unstable();
let n = position.len();
let mut low = std::i32::MAX;
for w in position.windows(2) {
low = low.min(w[1] - w[0]);
}
let mut high = (position[n - 1] - position[0]) / (m - 1) as i32;
while low < high {
let mid = (low + high + 1) / 2;
let mut prev = position[0];
let mut count = 1;
for i in 1..n {
if position[i] - prev >= mid {
count += 1;
prev = position[i];
}
}
if count < m {
high = mid - 1;
} else {
low = mid;
}
}
low
}
}
#[test]
fn test() {
let position = vec![1, 2, 3, 4, 7];
let m = 3;
let res = 3;
assert_eq!(Solution::max_distance(position, m), res);
let position = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let m = 4;
let res = 3;
assert_eq!(Solution::max_distance(position, m), res);
}
// Accepted solution for LeetCode #1552: Magnetic Force Between Two Balls
function maxDistance(position: number[], m: number): number {
position.sort((a, b) => a - b);
let [l, r] = [1, position.at(-1)!];
const count = (f: number): number => {
let cnt = 1;
let prev = position[0];
for (const curr of position) {
if (curr - prev >= f) {
cnt++;
prev = curr;
}
}
return cnt;
};
while (l < r) {
const mid = (l + r + 1) >> 1;
if (count(mid) >= m) {
l = mid;
} else {
r = mid - 1;
}
}
return l;
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.