KatInterview

Count Close Point Pairs Within Distance Threshold

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashingarrayshashinggeometry

Last 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.