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 of Points With Distance k INPUT 0 1 2 3 0 1 2 3 P0 P1 P2 P3 coordinates = [[1,2],[3,2],[1,3],[3,3]] k = 1 XOR Distance Formula: (x1 XOR x2) + (y1 XOR y2) must equal k ALGORITHM STEPS 1 Build HashMap Store (x,y) pairs as keys (1,2):1 (3,2):1 (1,3):1 (3,3):1 count occurrences 2 Iterate j: 0 to k Split k into j and (k-j) 3 Find Target Point x2 = x1 XOR j y2 = y1 XOR (k-j) 4 Lookup in HashMap Add count if (x2,y2) exists Example: P0(1,2), k=1 j=0: x2=1^0=1, y2=2^1=3 j=1: x2=1^1=0, y2=2^0=2 (1,3) found! Count++ FINAL RESULT Valid Pairs Found: Pair 1: P0(1,2) -- P2(1,3) P0 P2 (1^1)+(2^3)=0+1=1 OK Pair 2: P1(3,2) -- P3(3,3) P1 P3 (3^3)+(2^3)=0+1=1 OK Output: 2 Time: O(n * k) Space: O(n) Key Insight: Since XOR distance = (x1 XOR x2) + (y1 XOR y2) = k, we can split k into j and (k-j) for all j from 0 to k. For each point, compute target coordinates using XOR: x2 = x1 XOR j, y2 = y1 XOR (k-j). Use HashMap for O(1) lookup to check if target point exists, avoiding O(n^2) brute force comparison. TutorialsPoint - Count Pairs of Points With Distance k | Hash Map Optimization Approach
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