Count Pairs of Points With Distance k - Problem
You are given a 2D integer array coordinates and an integer k, where coordinates[i] = [xi, yi] are the coordinates of the i-th point in a 2D plane.
We define the distance between two points (x1, y1) and (x2, y2) as (x1 XOR x2) + (y1 XOR y2) where XOR is the bitwise XOR operation.
Return the number of pairs (i, j) such that i < j and the distance between points i and j is equal to k.
Input & Output
Example 1 — Basic Case
$
Input:
coordinates = [[1,2],[3,2],[1,3],[3,3]], k = 1
›
Output:
2
💡 Note:
Distance between [1,2] and [1,3]: (1⊕1)+(2⊕3) = 0+1 = 1. Distance between [3,2] and [3,3]: (3⊕3)+(2⊕3) = 0+1 = 1. Total pairs = 2.
Example 2 — No Pairs
$
Input:
coordinates = [[1,3],[1,3],[1,3],[1,4],[1,4],[1,4],[1,4]], k = 2
›
Output:
0
💡 Note:
Distance between any [1,3] and [1,4]: (1⊕1)+(3⊕4) = 0+7 = 7 ≠ 2. Distance between same coordinates is 0 ≠ 2. No pairs found.
Example 3 — All Same Points
$
Input:
coordinates = [[1,1],[1,1],[1,1]], k = 0
›
Output:
3
💡 Note:
Distance between any two identical points: (1⊕1)+(1⊕1) = 0+0 = 0 = k. We have 3 choose 2 = 3 pairs: (0,1), (0,2), (1,2).
Constraints
- 2 ≤ coordinates.length ≤ 104
- 0 ≤ coordinates[i][0], coordinates[i][1] ≤ 106
- 0 ≤ k ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Input
2D coordinates array and target distance k
2
XOR Distance
Calculate (x1⊕x2) + (y1⊕y2) for each pair
3
Count Matches
Count pairs where distance equals k
Key Takeaway
🎯 Key Insight: XOR distance enables efficient complement lookup using hash maps, reducing time complexity from O(n²) to O(n×k)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code