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
Difficulty
and has an acceptance rate of about 72% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Sorting
AI Disclaimer
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.
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
prevto a very small sentinel ensures the first basket is always considered for placement. - The early exit when
ballsreaches zero avoids unnecessary iteration over the remaining positions. - The comparison
p - prev >= distanceembodies 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), theputfunction will place balls at the earliest possible baskets, guaranteeing aTrueresult if the number of baskets is sufficient. - When the candidate distance approaches the total spread of positions, the early exit in
putquickly 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
prevensures 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 2064: Minimized Maximum of Products Distributed to Any Store
Solved On The Same Day
- problem 2529: Maximum Count of Positive Integer and Negative Integer
- problem 532: K-diff Pairs in an Array
- problem 718: Maximum Length of Repeated Subarray
- problem 826: Most Profit Assigning Work
- problem 1237: Find Positive Integer Solution for a Given Equation
- problem 1283: Find the Smallest Divisor Given a Threshold
- problem 1561: Maximum Number of Coins You Can Get
- problem 1760: Minimum Limit of Balls in a Bag
- problem 1870: Minimum Speed to Arrive on Time
Extra
- 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