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
Count Pairs with XOR Distance kInput Points[1,2], [3,2][1,3], [3,3]k = 1XOR Distance FormulaDistance = (x1 ⊕ x2) + (y1 ⊕ y2)[1,2] & [1,3]: (1⊕1)+(2⊕3) = 0+1 = 1 ✓[3,2] & [3,3]: (3⊕3)+(2⊕3) = 0+1 = 1 ✓Result2 pairsXOR Properties: x ⊕ x = 0, x ⊕ 0 = x, commutative and associative💡 Key Insight: XOR distance creates unique patterns that allowefficient complement calculation instead of checking all pairs
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)
Asked in
Google 15 Microsoft 12 Amazon 8
15.2K Views
Medium Frequency
~25 min Avg. Time
486 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen