#3809
Best Reachable Tower
MediumArrayHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
We can efficiently find the best tower by iterating through the list once, checking distances and updating the best tower based on quality and coordinates.
⚙️
Algorithm
3 steps- 1Step 1: Initialize best tower coordinates and max quality.
- 2Step 2: Loop through each tower, compute Manhattan distance.
- 3Step 3: Update best tower if it's reachable and has higher quality or is lexicographically smaller.
solution.py10 lines
1def bestReachableTower(towers, center, radius):
2 best = [-1, -1]
3 max_quality = -1
4 for x, y, q in towers:
5 dist = abs(x - center[0]) + abs(y - center[1])
6 if dist <= radius:
7 if q > max_quality or (q == max_quality and (best[0] == -1 or (x < best[0] or (x == best[0] and y < best[1])))):
8 best = [x, y]
9 max_quality = q
10 return bestℹ
Complexity note: We only traverse the list of towers once, making the time complexity linear.
- 1Understanding Manhattan distance is crucial.
- 2Quality and coordinates must be compared correctly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.