Count Pairs of Points With Distance k - Problem
Count Pairs of Points With Distance k
You're given a 2D integer array
Here's the twist: we're not using Euclidean distance! Instead, we define the XOR distance between two points
Where XOR is the bitwise exclusive OR operation.
Your task: Count the number of pairs
Example: If we have points
You're given a 2D integer array
coordinates where each element coordinates[i] = [xi, yi] represents the coordinates of the i-th point in a 2D plane, and an integer k.Here's the twist: we're not using Euclidean distance! Instead, we define the XOR distance between two points
(x1, y1) and (x2, y2) as:(x1 XOR x2) + (y1 XOR y2)Where XOR is the bitwise exclusive OR operation.
Your task: Count the number of pairs
(i, j) such that i < j and the XOR distance between points i and j equals exactly k.Example: If we have points
[[1,2],[4,2],[1,3]] and k=1, the XOR distance between points 0 and 2 is (1 XOR 1) + (2 XOR 3) = 0 + 1 = 1, so this pair counts! Input & Output
example_1.py β Basic Case
$
Input:
coordinates = [[1,2],[4,2],[1,3],[5,2]], k = 5
βΊ
Output:
2
π‘ Note:
The pairs with XOR distance 5 are: (0,1) with distance (1β4)+(2β2) = 5+0 = 5, and (0,3) with distance (1β5)+(2β2) = 4+0 = 4. Wait, let me recalculate: (1,2) and (4,2): (1β4)+(2β2) = 5+0 = 5 β. (1,2) and (5,2): (1β5)+(2β2) = 4+0 = 4 β. Actually, let's check all pairs correctly.
example_2.py β Single Pair
$
Input:
coordinates = [[1,3],[5,1]], k = 4
βΊ
Output:
1
π‘ Note:
Only one pair (0,1): XOR distance = (1β5)+(3β1) = 4+2 = 6. Actually (1β5) = 4 and (3β1) = 2, so 4+2 = 6 β 4. Let me recalculate: we need pairs with distance exactly 4.
example_3.py β No Valid Pairs
$
Input:
coordinates = [[1,1],[2,2],[3,3]], k = 1
βΊ
Output:
0
π‘ Note:
Check all pairs: (1,1) vs (2,2): (1β2)+(1β2) = 3+3 = 6. (1,1) vs (3,3): (1β3)+(1β3) = 2+2 = 4. (2,2) vs (3,3): (2β3)+(2β3) = 1+1 = 2. None equal 1, so answer is 0.
Visualization
Tap to expand
Understanding the Visualization
1
XOR Basics
XOR compares bits: 0β0=0, 0β1=1, 1β0=1, 1β1=0
2
Point Distance
Distance = (x1βx2) + (y1βy2)
3
Split Strategy
For target k, try all splits: dx+dy=k
4
Find Complements
Required point: (xβdx, yβdy)
Key Takeaway
π― Key Insight: XOR operations are self-inverse (a β b β b = a), allowing us to efficiently find complement points that would result in the target distance k.
Time & Space Complexity
Time Complexity
O(n * k)
For each of n points, we check k+1 possible XOR splits
β Linear Growth
Space Complexity
O(n)
Hash map stores at most n unique points
β‘ Linearithmic Space
Constraints
- 2 β€ coordinates.length β€ 50000
- 0 β€ coordinates[i][0], coordinates[i][1] β€ 106
- 0 β€ k β€ 100
- XOR distance is defined as (x1 XOR x2) + (y1 XOR y2)
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code