1413. Manhattan Within Reach
Delivery scooters ride on a street grid, so the distance between two positions is the Manhattan distance |dx| + |dy|. Given the scooter positions points (each [x, y]) and a radio range d, count the unordered pairs of different indices whose Manhattan distance is at most d, and return the count as a long. Scooters may share a position.
Rotate the plane with u = x + y and v = x - y: the condition becomes |du| <= d and |dv| <= d. Sort by u, slide a window of u-width d, and count the window members whose v lies in [v - d, v + d] with a Fenwick tree over compressed v values. The answer can exceed 32 bits. The intended solution runs in O(n log n) time and O(n) space.
Example 1
- Input:
- points = [[0,0],[1,1],[3,0],[0,5]], d = 2
- Output:
- 1
- Explanation:
Only the pair (0, 0) and (1, 1) is within Manhattan distance 2.
Example 2
- Input:
- points = [[2,2],[2,2],[2,2],[3,3]], d = 0
- Output:
- 3
- Explanation:
With d = 0 only the three copies of (2, 2) pair up, giving 3 pairs.
Example 3
- Input:
- points = [[0,0],[5,5],[-5,5]], d = 20
- Output:
- 3
- Explanation:
Every pair is at Manhattan distance at most 10, so all 3 pairs count.
Constraints
1 ≤ n ≤ 105
-108 ≤ x, y ≤ 108
0 ≤ d ≤ 109
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 10,000 msC++ 2,500 msJava 5,000 msJavaScript 5,000 msTypeScript 5,000 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)