Queries on Number of Points Inside a Circle - Problem

You are given an array points where points[i] = [xi, yi] represents 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] = [xj, yj, rj] describes a circle centered at (xj, yj) with a radius of rj.

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.

Input & Output

Example 1 — Basic Case
$ Input: points = [[1,3],[3,3],[5,3],[2,2]], queries = [[2,3,1],[4,3,1]]
Output: [3,2]
💡 Note: For query [2,3,1]: Points [1,3], [3,3], [2,2] are within distance 1 of center (2,3). For query [4,3,1]: Points [3,3], [5,3] are within distance 1 of center (4,3).
Example 2 — Points on Border
$ Input: points = [[1,1],[2,2],[3,3]], queries = [[1,1,1]]
Output: [1]
💡 Note: Point [1,1] is at center (distance 0), point [2,2] is at distance √2 ≈ 1.41 > 1, point [3,3] is at distance √8 ≈ 2.83 > 1. Only [1,1] is within radius 1.
Example 3 — Large Radius
$ Input: points = [[1,1],[2,2],[3,3]], queries = [[2,2,2]]
Output: [3]
💡 Note: All points [1,1], [2,2], [3,3] are within distance 2 of center (2,2). Distances are √2, 0, √2 respectively, all ≤ 2.

Constraints

  • 1 ≤ points.length ≤ 500
  • points[i].length == 2
  • 1 ≤ queries.length ≤ 500
  • queries[j].length == 3
  • 0 ≤ xi, yi, xj, yj ≤ 500
  • 1 ≤ rj ≤ 500

Visualization

Tap to expand
Queries on Number of Points Inside a Circle INPUT 1 2 3 4 5 3 2 1 (1,3) (3,3) (5,3) (2,2) Points Array: [[1,3],[3,3],[5,3],[2,2]] Queries Array: [[2,3,1],[4,3,1]] center(x,y), radius r ALGORITHM STEPS 1 For each query Get center (xj,yj) and radius rj 2 For each point Calculate dx = xi - xj, dy = yi - yj 3 Squared Distance dist_sq = dx*dx + dy*dy 4 Check if inside If dist_sq <= r*r, count++ Query 1: center(2,3), r=1 Point(1,3): (1-2)^2+(3-3)^2=1 OK Point(3,3): (3-2)^2+(3-3)^2=1 OK Point(5,3): (5-2)^2+(3-3)^2=9 NO Point(2,2): (2-2)^2+(2-3)^2=1 OK r^2 = 1, Count = 3 Query 2: center(4,3), r=1 Count = 2 (points 3,3 and 5,3) FINAL RESULT Query 1: 3 points inside Query 2: 2 points inside Output Array: [3, 2] answer[0] = 3 answer[1] = 2 Solution Complete! Key Insight: Squared Distance Optimization Instead of calculating sqrt(dx^2 + dy^2) <= r, we compare dx^2 + dy^2 <= r^2 directly. This avoids expensive square root operations while preserving correctness. Time Complexity: O(Q * P) where Q = queries, P = points. Space: O(Q) for result array. TutorialsPoint - Queries on Number of Points Inside a Circle | Squared Distance Approach
Asked in
Google 25 Microsoft 18 Amazon 15
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen