Count Pairs of Points Within 2 Units on Both Axes
Capital OneSoftware Engineer · Online AssessmentLast updated
A coding question that asks how many pairs of points intersect, where two points intersect when both their x-coordinates and their y-coordinates differ by at most 2. It tests counting unordered pairs with duplicate points, inclusive bounds and scaling to 100,000 points with large coordinates.
You are given a list of points on a plane with integer coordinates. Two points intersect when their x-coordinates differ by at most 2 and their y-coordinates also differ by at most 2. Return the number of pairs of points that intersect.
Function Signature
def count_intersecting_pairs(points: list[list[int]]) -> int:
Rules
- Each point is given as
[x, y]. - Points
iandjintersect whenabs(x_i - x_j) <= 2andabs(y_i - y_j) <= 2; both bounds are inclusive. - Count unordered pairs of different indices
i < j, each pair once. A point is never paired with itself. - Points may repeat: two points at the same coordinates are different points, and they intersect.
Constraints
1 <= len(points) <= 10^5-10^9 <= x, y <= 10^9- the answer can reach
n * (n - 1) / 2, about5 * 10^9when all points coincide, which exceeds2^31 - 1; return it as an exact integer
Examples
Example 1
Input: points = [[0, 0], [2, 2], [3, 0], [5, 5]]
Output: 2
[0, 0] and [2, 2] differ by 2 on both axes, and [2, 2] and [3, 0] differ by 1 and 2. Every other pair differs by more than 2 on at least one axis.
Example 2
Input: points = [[1, 1], [1, 1], [1, 4]]
Output: 1
The two copies of [1, 1] intersect; [1, 4] is 3 away from both on the y-axis.
Example 3
Input: points = [[0, 0]]
Output: 0
A single point forms no pairs.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.