1369. Too Close for Comfort
A drone show planner stores the planned positions of the drones as integer points points[i] = [x, y] on a flat map. Two drones are too close when their squared Euclidean distance is strictly smaller than d * d. Two drones that share exactly the same position are too close for every valid d.
Return true if any two different indices are too close, otherwise false. Checking all pairs is O(n^2) and too slow. Instead, hash every point into a square grid cell of side d, using mathematical floor division so negative coordinates fall into the correct cell. Only the 3 x 3 block of cells around a point can hold a close partner, and a cell can contain only a constant number of points before a close pair appears, so the expected time is O(n). Squared distances need 64-bit arithmetic.
Example 1
- Input:
- points = [[0,0],[3,4]], d = 5
- Output:
- false
- Explanation:
The squared distance is 25, which is not below 5 * 5 = 25, so the pair is not close.
Example 2
- Input:
- points = [[0,0],[3,4]], d = 6
- Output:
- true
- Explanation:
The squared distance 25 is below 36, so the pair is close.
Example 3
- Input:
- points = [[1,1],[1,1],[10,10]], d = 1
- Output:
- true
- Explanation:
The first two points are identical, so their distance 0 is below d.
Constraints
- 2 ≤ n ≤ 105, where n is the number of points
- points[i].length == 2
- -106 ≤ x, y ≤ 106
- 1 ≤ d ≤ 106
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)