Queries on Number of Points Inside a Circle Problem
Description
LeetCode Problem 1828.
You are given an array points where points[i] = [x_i, y_i] is the coordinates of the i^th point on a 2D plane. Multiple points can have the same coordinates.
You are also given an array queries where queries[j] = [x_j, y_j, r_j] describes a circle centered at (x_j, y_j) with a radius of r_j.
For each query queries[j], compute the number of points inside the j^th circle. Points on the border of the circle are considered inside.
Return an array answer, where answer[j] is the answer to the j^th query.
Example 1:

Input: points = [[1,3],[3,3],[5,3],[2,2]], queries = [[2,3,1],[4,3,1],[1,1,2]]
Output: [3,2,2]
Explanation: The points and circles are shown above.
queries[0] is the green circle, queries[1] is the red circle, and queries[2] is the blue circle.
Example 2:

Input: points = [[1,1],[2,2],[3,3],[4,4],[5,5]], queries = [[1,2,2],[2,2,2],[4,3,2],[4,3,3]]
Output: [2,3,2,4]
Explanation: The points and circles are shown above.
queries[0] is green, queries[1] is red, queries[2] is blue, and queries[3] is purple.
Constraints:
1 <= points.length <= 500points[i].length == 20 <= x_i, y_i <= 5001 <= queries.length <= 500queries[j].length == 30 <= x_j, y_j <= 5001 <= r_j <= 500- All coordinates are integers.
Follow up: Could you find the answer for each query in better complexity than O(n)?
Solution
Approach: Brute-Force Enumeration
Both arrays are small (at most 500 entries each), so we can test every point against every circle. A point (px, py) is inside the circle (x, y, r) when (x - px)^2 + (y - py)^2 <= r^2. Comparing squared values keeps everything in integers. Count the points that pass for each query.
Complexity: O(m * n) time and O(1) extra space besides the answer, where m is the number of queries and n the number of points.
class Solution:
def countPoints(
self, points: List[List[int]], queries: List[List[int]]
) -> List[int]:
ans = []
for x, y, r in queries:
cnt = 0
for i, j in points:
dx, dy = i - x, j - y
cnt += dx * dx + dy * dy <= r * r
ans.append(cnt)
return ans