Problem 1552

Abstract / Summary

Calculate the force between two magnetic balls based on their positions and charges.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1552.py

class Solution:
    def maxDistance(self, position: List[int], m: int) -> int:
        position.sort()

        # try to put balls into baskets and ensure minimum distance, return True if possible
        def put(distance):
            balls = m

            # always put a ball into the first basket
            prev = -10**11
            for p in position:
                if p - prev >= distance:
                    # store ball
                    prev   = p
                    balls -= 1
                    if balls == 0:
                        return True

            return False

        # binary search
        width = position[-1] - position[0]
        left  = 1
        right = width // (m - 1) # equidistant if enough baskets at good positions
        while left != right:
            mid = (left + right) // 2
            if put(mid):
                # balls could to be farther away
                left  = mid + 1
            else:
                # need shorter distance, not all balls fit into baskets
                right = mid

        return left if put(left) else left - 1
34 lines | 1134 bytes | submitted November 24, 2023 | GitHub   30% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 72% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the problem of placing m balls into a set of baskets positioned along a line such that the minimum distance between any two balls is maximized. The algorithm follows a classic pattern: it first orders the basket positions, then uses a feasibility check combined with binary search to locate the largest distance that still allows all balls to be placed.

Sorting the Positions

The first operation arranges the basket coordinates in non-decreasing order, which is essential for the greedy placement strategy that follows.

position.sort()

By sorting once, the later steps can rely on a predictable traversal order, eliminating the need for repeated ordering and enabling efficient distance checks.

Feasibility Check (put Function)

A nested helper function named put determines whether a given candidate distance can accommodate all m balls. It iterates through the sorted positions, placing a ball whenever the distance from the previously placed ball meets or exceeds the candidate value. The function stops early as soon as all balls have been placed, returning True. If the loop finishes without placing all balls, it returns False.

def put(distance):
    balls = m
    prev = -10**11
    for p in position:
        if p - prev >= distance:
            prev = p
            balls -= 1
            if balls == 0:
                return True
    return False

Key aspects of this routine include:

  • Initialization of prev to a very small sentinel ensures the first basket is always considered for placement.
  • The early exit when balls reaches zero avoids unnecessary iteration over the remaining positions.
  • The comparison p - prev >= distance embodies the greedy principle that placing a ball at the earliest feasible location leaves maximal room for subsequent balls.

Determining Search Bounds

Before launching the binary search, the algorithm computes a search interval for the distance. The lower bound starts at 1, representing the smallest positive integer distance that could be meaningful. The upper bound is derived from the total spread of basket positions divided by m-1, reflecting the scenario where balls are evenly spaced across the extreme baskets.

width = position[-1] - position[0]
left  = 1
right = width // (m - 1)

This calculation narrows the search space to a realistic range, preventing the binary search from exploring distances that are provably unattainable.

Binary Search Loop

The core of the algorithm is a binary search that repeatedly probes the midpoint of the current interval. For each midpoint, the put function assesses feasibility:

  • If placement succeeds, the algorithm knows a larger distance might still be possible, so it moves the lower bound up.
  • If placement fails, the upper bound is reduced to the midpoint, indicating that the distance is too large.

The loop continues until the lower and upper bounds converge.

while left != right:
    mid = (left + right) // 2
    if put(mid):
        left = mid + 1
    else:
        right = mid

The condition left != right guarantees termination when the interval cannot be subdivided further.

Final Result Selection

After the loop, the algorithm performs a final feasibility check on the converged value. If the distance left is still viable, it is returned; otherwise, the algorithm steps back by one unit, delivering the greatest distance that succeeded.

return left if put(left) else left - 1

This final verification ensures correctness even when the binary search overshoots the exact maximum distance by one step.

Edge Cases Handled

The implementation gracefully manages several boundary situations:

  • When the candidate distance is minimal (e.g., 1), the put function will place balls at the earliest possible baskets, guaranteeing a True result if the number of baskets is sufficient.
  • When the candidate distance approaches the total spread of positions, the early exit in put quickly determines infeasibility without scanning the entire list.
  • The use of integer division for the upper bound automatically truncates fractional distances, aligning the search with the integer nature of basket coordinates.
  • The sentinel value for prev ensures that the first basket is always eligible for placement, covering the case where the smallest distance is larger than any gap between consecutive baskets.

Performance Optimizations

Several design choices contribute to an efficient execution profile:

  • Sorting is performed a single time, avoiding repeated ordering operations during the binary search.
  • The feasibility check employs a greedy scan that stops as soon as all balls are placed, reducing the average number of iterations especially when the candidate distance is small.
  • The upper bound calculation leverages the overall width of the positions, tightening the initial search interval and decreasing the number of binary search steps required.
  • By using integer arithmetic throughout, the algorithm sidesteps the overhead of floating-point operations.

Collectively, these optimizations enable the solution to handle large input sizes with minimal computational waste while preserving clarity and correctness.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long row of baskets sitting in your room. Some are close together and some are far apart. You have a handful of bouncy balls and you want to put them into these baskets so that every ball is as far away from its neighbor as possible.

The code starts by lining the baskets up in order, from the one at the very start to the one at the very end.

The first helper part of the code acts like a little game. It asks if it is possible to fit all the balls into the baskets while keeping a certain amount of space between each one. It tries to place each ball, one by one, into a basket that is far enough away from the last one used. If all the balls find a home, the game lets out a happy signal.

The second big part of the code is like a game of higher or lower. Because searching through every single possibility would take too long, the computer picks a middle distance to test first. If the balls fit with that much space, the computer knows it can try to stretch them out even further, so it looks at the bigger half of the options. If the balls keep bumping into each other and won't fit, the computer knows it needs to pull them closer together and looks at the smaller half instead.

By playing this back and forth game, the code very quickly finds the perfect distance that keeps those balls as spread out as they can possibly be. It keeps narrowing down the options until it finds the best one.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.59 | σ = 0.95

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python JS Java Go TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
27 links | 15 authors | 7 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

10 solutions   November 24, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality