#1453
Maximum Number of Darts Inside of a Circular Dartboard
HardArrayMathGeometryGeometryBrute ForceTwo Pointers
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)
The optimal approach leverages the geometric properties of circles. By focusing on pairs of darts and calculating potential circle centers, we can efficiently determine how many darts can fit within the radius without redundant calculations.
⚙️
Algorithm
4 steps- 1Step 1: For each pair of darts, calculate the distance between them.
- 2Step 2: If the distance is less than or equal to 2 * r, calculate the two possible circle centers that can encompass both darts.
- 3Step 3: For each center, count how many darts are within the radius r.
- 4Step 4: Keep track of the maximum count of darts found.
solution.py22 lines
1# Full working Python code
2import math
3
4def maxDartsInside(darts, r):
5 def countDarts(center):
6 return sum(1 for x, y in darts if math.sqrt((x - center[0]) ** 2 + (y - center[1]) ** 2) <= r)
7
8 max_count = 0
9 n = len(darts)
10 for i in range(n):
11 for j in range(i + 1, n):
12 x1, y1 = darts[i]
13 x2, y2 = darts[j]
14 d = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
15 if d > 2 * r:
16 continue
17 mid_x, mid_y = (x1 + x2) / 2, (y1 + y2) / 2
18 h = math.sqrt(r ** 2 - (d / 2) ** 2)
19 center1 = (mid_x + h * (y2 - y1) / d, mid_y - h * (x2 - x1) / d)
20 center2 = (mid_x - h * (y2 - y1) / d, mid_y + h * (x2 - x1) / d)
21 max_count = max(max_count, countDarts(center1), countDarts(center2))
22 return max_countℹ
Complexity note: The time complexity remains O(n²) due to the nested loops for pairs of darts, but we efficiently calculate potential circle centers and dart counts, minimizing unnecessary checks. The space complexity is O(1) as we only use a few variables.
- 1The maximum number of darts can be achieved by strategically placing the circle's center based on the positions of the darts.
- 2When the distance between two darts is less than or equal to 2 * r, it is possible to encompass both within a single circle.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.