Maximum Number of Darts Inside of a Circular Dartboard Problem
Description
LeetCode Problem 1453.
Alice is throwing n darts on a very large wall. You are given an array darts where darts[i] = [x_i, y_i] is the position of the i^th dart that Alice threw on the wall.
Bob knows the positions of the n darts on the wall. He wants to place a dartboard of radius r on the wall so that the maximum number of darts that Alice throws lie on the dartboard.
Given the integer r, return the maximum number of darts that can lie on the dartboard.
Example 1:

Input: darts = [[-2,0],[2,0],[0,2],[0,-2]], r = 2
Output: 4
Explanation: Circle dartboard with center in (0,0) and radius = 2 contain all points.
Example 2:

Input: darts = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5
Output: 5
Explanation: Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8).
Constraints:
1 <= darts.length <= 100darts[i].length == 2-10^4 <= x_i, y_i <= 10^4- All the
dartsare unique 1 <= r <= 5000
Solution
Approach: Circles Through Two Darts
Take a best placement of the dartboard. We can slide it, without losing any dart, until its edge touches two darts (if it ever covers at least two). So it is enough to try the circles of radius r whose edge passes through two of the darts.
For two darts at distance d:
- if
d > 2r, no such circle exists; - otherwise there are two centers (one when
d = 2r). Both lie on the perpendicular bisector of the two darts, at distancesqrt(r^2 - d^2/4)from their midpoint, one on each side.
For each candidate center, count the darts within distance r. The answer is the largest count, and at least 1, since a single dart always fits (that also covers n = 1 and darts that are all far apart).
The tricky part is floating point. The candidate circles go exactly through darts, so the two defining darts (and often others) lie exactly on the edge, and rounding can put them a hair outside. Comparing the squared distance with r^2 + 1e-6 keeps them. The d > 2r test is done on integers (d^2 > 4r^2) so it is exact.
Complexity: O(n3) time (n2 pairs, two centers each, n darts to count) and O(1) extra space.
from math import sqrt
class Solution:
def numPoints(self, darts: List[List[int]], r: int) -> int:
def count(cx: float, cy: float) -> int:
# A small tolerance keeps darts that lie exactly on the edge.
return sum((x - cx) ** 2 + (y - cy) ** 2 <= r * r + 1e-6 for x, y in darts)
ans = 1 # one dart always fits
n = len(darts)
for i in range(n):
x1, y1 = darts[i]
for j in range(i + 1, n):
x2, y2 = darts[j]
dx, dy = x2 - x1, y2 - y1
d2 = dx * dx + dy * dy
if d2 > 4 * r * r:
continue # too far apart for one circle of radius r to pass through both
# The two centers lie on the perpendicular bisector, sqrt(r^2 - d^2/4) from the midpoint.
h = sqrt((4 * r * r - d2) / (4 * d2)) # that distance divided by d
mx, my = (x1 + x2) / 2, (y1 + y2) / 2
ox, oy = -dy * h, dx * h
ans = max(ans, count(mx + ox, my + oy), count(mx - ox, my - oy))
return ans