Python 1620.py
class Solution:
def bestCoordinate(self, towers: List[List[int]], radius: int) -> List[int]:
# max. area
x1 = x2 = towers[0][0]
y1 = y2 = towers[0][0]
for x, y, q in towers:
x1 = min(x1, x)
x2 = max(x2, x)
y1 = min(y1, y)
y2 = max(y2, y)
radius2 = radius * radius
strength = 0
location = [ 0, 0 ]
for x in range(x1, x2+1): # order of loops ensures lexicographical order
for y in range(y1, y2+1):
total = 0
for tx, ty, q in towers:
# too far ?
dx = abs(x - tx)
dy = abs(y - ty)
dist2 = dx*dx + dy*dy
if dist2 > radius2: # faster if both sides are squared
continue
signal = q / (1 + sqrt(dist2))
total += int(signal) # round down, only seen in the example
if strength < total:
strength = total
location = [ x, y ]
return location
Difficulty
and has an acceptance rate of about 40% (30k+ submissions).
Typical patterns to solve this problem:
- Array
- Enumeration
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 computes the integer coordinate within the smallest axis-aligned rectangle that encloses all towers, where the summed signal strength from the towers is maximized. The signal contributed by a tower decays with Euclidean distance and is truncated to an integer by rounding down. The algorithm explores every integer point inside the bounding rectangle, evaluates the cumulative signal from all towers that lie within the given radius, and retains the point with the highest total strength. Lexicographical ordering of coordinates is naturally enforced by the nested loop order.
Determining the Search Bounds
The first phase identifies the minimum and maximum x- and y-coordinates among the towers. This defines a rectangular region that certainly contains the optimal point, because any point outside this rectangle would be farther from every tower than at least one point on its border.
x1 = x2 = towers[0][0]
y1 = y2 = towers[0][0]
for x, y, q in towers:
x1 = min(x1, x)
x2 = max(x2, x)
y1 = min(y1, y)
y2 = max(y2, y)
By initializing the bounds with the first tower’s coordinates, the code avoids an extra pass for empty input and guarantees that the variables are defined before the loop.
Pre-computing the Radius Squared
To avoid repeated square-root operations when checking whether a tower lies within the radius, the squared radius is stored. The distance comparison is performed on squared values, which is faster because it eliminates the need for a costly square-root in the early filter.
radius2 = radius * radius
Exhaustive Evaluation of Candidate Points
The core of the algorithm iterates over every integer coordinate (x, y) inside the bounding rectangle. The outer loop runs over x, the inner loop over y, which yields points in lexicographical order (first by x, then by y). For each candidate point, the total signal is accumulated by iterating over all towers.
strength = 0
location = [0, 0]
for x in range(x1, x2 + 1):
for y in range(y1, y2 + 1):
total = 0
for tx, ty, q in towers:
dx = abs(x - tx)
dy = abs(y - ty)
dist2 = dx * dx + dy * dy
if dist2 > radius2:
continue
signal = q / (1 + sqrt(dist2))
total += int(signal)
if strength < total:
strength = total
location = [x, y]
Distance Filtering
The distance check if dist2 > radius2: continue discards towers that are definitely out of range before any division or square-root is performed. This early exit reduces the amount of arithmetic for distant towers.
Signal Computation and Truncation
When a tower is within range, the signal is calculated as q / (1 + sqrt(dist2)). The sqrt call is only executed after the distance filter, ensuring it is invoked only for relevant towers. The result is truncated to an integer using int(signal), matching the problem’s specification that the signal is rounded down.
Updating the Best Location
The condition if strength < total: updates the stored best strength and its coordinates only when a strictly larger total is found. Because the loops iterate in lexicographical order, ties automatically preserve the earlier (smaller) coordinate without additional comparison logic.
Edge Cases Handled
When there is only a single tower, the bounding rectangle collapses to a single point, and the loops evaluate exactly that coordinate, correctly returning it as the optimal location. If the radius is zero, only points that coincide exactly with a tower’s position satisfy the distance filter, and the algorithm still returns the coordinate with the highest tower quality after truncation. Towers that share identical coordinates are processed individually; their qualities are summed because each iteration adds the truncated signal from each tower, effectively handling overlapping towers. The code also works when all towers have the same quality value, as the comparison relies solely on the summed signal.
Performance Optimizations
The algorithm incorporates several practical optimizations. Bounding the search to the minimal rectangle eliminates unnecessary exploration of the infinite plane. Using squared distances for the initial range check avoids expensive square-root operations for towers that are out of range. The early continue statement prevents the division and square-root from being executed for those towers. Storing the radius squared once avoids recomputation inside the innermost loop. The nested loop order guarantees lexicographical ordering without extra sorting or comparison steps. Finally, converting the floating-point signal to an integer with int(signal) directly discards the fractional part, which is both required by the specification and computationally cheap.
Overall, the implementation balances exhaustive search with targeted pruning, delivering correct results while minimizing unnecessary arithmetic.
ELI5 - Simplified Explanation
Imagine that there are several magical towers scattered across a large treasure map. Each tower shines with a little bit of light, and the goal is to find the perfect spot on the map where the light is the brightest.
First, the computer looks at all the towers to see how far spread out they are. It finds the very leftmost, rightmost, topmost, and bottommost edges so it knows exactly where to search on the whole map.
After finding the boundaries, the computer starts a big treasure hunt. It visits every single square on the map, starting from the corner. For every spot it visits, it pretends to stand there and checks every tower. It calculates how much light reaches that spot from each tower. The closer a tower is, the more light it gives. If a tower is too far away, it is ignored because its light cannot reach that far.
As the computer visits each square, it keeps a running total of all the light brightness. If it finds a spot that is brighter than any other spot it has seen before, it remembers that spot as the new best place to be. By the time it finishes checking every single square on the map, it knows exactly which location has the most light.
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++ | Java | Python | TS | |||
| WalkCCC | C++ | Java | Python | |||||
| leetcode.ca | C++ | Java | Go | Python | ||||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| suxrobGM | C# | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| suxrobGM | C# |
Videos
Solved On The Same Day
- problem 811: Subdomain Visit Count
- problem 900: RLE Iterator
- problem 945: Minimum Increment to Make Array Unique
- problem 949: Largest Time for Given Digits
- problem 2240: Number of Ways to Buy Pens and Pencils
- problem 2249: Count Lattice Points Inside a Circle
- problem 2261: K Divisible Elements Subarrays
- problem 2310: Sum of Numbers With Units Digit K
- problem 2735: Collecting Chocolates
- problem 2800: Shortest String That Contains Three Strings
- problem 2306: Naming a Company
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