Count Close Point Pairs Within Distance Threshold
Arrays & HashingAuto-graded · 23 test casesLast updated
Efficiently count pairs of points where both coordinate differences are at most 2, testing hash-based spatial grouping with duplicate handling.
You are given a collection of points on a 2D plane, each represented by integer coordinates. Your task is to count how many pairs of points are "close" to each other.
Two points are considered close when the absolute difference between their x-coordinates is at most 2 and the absolute difference between their y-coordinates is also at most 2. Both conditions must be satisfied simultaneously.
Count each unordered pair exactly once. If multiple points share the same coordinates, treat them as distinct points—each gets its own index, and any two of them form a valid pair if they are close.
Constraints
1 <= len(points) <= 10^5- Each point is represented as
[x, y]where-10^9 <= x, y <= 10^9 - The result fits in a Python integer but may exceed 32-bit signed range (up to approximately
5 * 10^9) - Points at identical coordinates are treated as different points
Examples
Example 1
Input: count_close_pairs([[0, 0], [2, 2], [3, 0], [5, 5]])
Output: 2
Example 2
Input: count_close_pairs([[1, 1], [1, 1], [1, 4]])
Output: 1
Example 3
Input: count_close_pairs([[0, 0]])
Output: 0
Hints
Hint 1
The naive O(n²) pairwise comparison is too slow for 100,000 points. Can you avoid checking every pair?
Hint 2
Two points can only be close if their coordinate difference falls within a small fixed window. How many possible offset vectors are there?
Hint 3
Use a hash map to group points by their exact coordinates, then probe only the nearby coordinates that could possibly be close.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The brute-force solution of checking all n(n-1)/2 pairs becomes prohibitively slow at n = 100,000, requiring around 5 billion comparisons. The key insight is that the "closeness" window is tiny and fixed in size.
Two points can only be close if their coordinate offset (dx, dy) satisfies |dx| <= 2 and |dy| <= 2. This defines a 5×5 grid of possible offsets—just 25 positions in total, including (0, 0) for identical coordinates.
Rather than searching through all points for neighbors, we can look them up directly:
-
Group by coordinates: Use a hash map to count how many points exist at each distinct coordinate
(x, y). -
Count within-group pairs: If
cpoints share the same coordinates, they all form close pairs with each other. The number of unordered pairs within a group isc * (c - 1) / 2. -
Count cross-group pairs: For each distinct coordinate
(x, y)with countc, probe the 24 non-zero offsets in the 5×5 window. For each neighboring coordinate(x + dx, y + dy)that exists with counto, addc * opairs (every point at the first coordinate pairs with every point at the second).
To avoid counting each cross-group pair twice, we probe only offsets that are lexicographically greater than (0, 0). In Python, this is simply (dx, dy) > (0, 0), which captures:
- All offsets with
dx > 0(10 offsets:dxfrom 1 to 2,dyfrom -2 to 2) - Offsets with
dx == 0anddy > 0(2 offsets:dyfrom 1 to 2)
This gives exactly 12 offsets. Each pair of distinct coordinates is encountered exactly once: when we process the coordinate that comes first lexicographically, we find its lexicographically-later neighbor.
Why It Works
-
Same coordinates: Points at the same position always satisfy the closeness condition (difference of 0 on both axes). The formula
c(c-1)/2counts all unordered pairs within that group. -
Different coordinates: For any pair at positions
pandqwithp ≠ q, the offsetd = q - pis non-zero. Exactly one ofdor-dis lexicographically positive. When we process the smaller coordinate (in lexicographic order), we probe the positive offset and discover the larger coordinate, counting the pair exactly once. -
Non-close pairs: Only offsets within the 5×5 window are probed, so pairs that differ by more than 2 on any axis are never counted.
Complexity
- Time:
O(n). Building the counter takesO(n). Each of at mostndistinct coordinates performs 12 constant-time hash lookups. - Space:
O(n)for the hash map storing coordinate counts.
The massive coordinate range (up to 10^9) is irrelevant because we never construct a grid—we only hash the coordinates that actually appear in the input.
Solution
from collections import Counter
from typing import List
def count_close_pairs(points: List[List[int]]) -> int:
cnt = Counter((x, y) for x, y in points)
total = 0
offs = [(dx, dy) for dx in range(-2, 3) for dy in range(-2, 3) if (dx, dy) > (0, 0)]
for (x, y), c in cnt.items():
total += c * (c - 1) // 2
for dx, dy in offs:
o = cnt.get((x + dx, y + dy))
if o:
total += c * o
return total