#1828
Queries on Number of Points Inside a Circle
MediumArrayMathGeometry
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n + m log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n + m log n)Space O(n)
We can optimize the search by precomputing the distances of points from the origin and using a spatial data structure or sorting to quickly find how many points are within each query circle.
⚙️
Algorithm
4 steps- 1Step 1: Create a list of squared distances for all points from the origin.
- 2Step 2: Sort this list of squared distances.
- 3Step 3: For each query, calculate the squared radius and use binary search to find how many points have squared distances less than or equal to this squared radius.
- 4Step 4: Store the results for each query and return the result list.
solution.py13 lines
1# Full working Python code
2from bisect import bisect_right
3
4def countPoints(points, queries):
5 distances = sorted((x**2 + y**2) for x, y in points)
6 result = []
7 for (xj, yj, rj) in queries:
8 r_squared = rj * rj
9 count = bisect_right(distances, r_squared)
10 result.append(count)
11 return result
12
13print(countPoints([[1,3],[3,3],[5,3],[2,2]], [[2,3,1],[4,3,1],[1,1,2]]))ℹ
Complexity note: The sorting step takes O(n log n), and each query takes O(log n) due to binary search, making it efficient for multiple queries.
- 1Understanding the geometry of circles and points is crucial.
- 2Using sorting and binary search can significantly reduce the time complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.