Magicsheet logo

Count Pairs of Points With Distance k

Medium
25%
Updated 8/1/2025

Count Pairs of Points With Distance k

What is this problem about?

The "Count Pairs of Points With Distance k interview question" defines distance between two points (x1,y1)(x1, y1) and (x2,y2)(x2, y2) using the XOR operator: (x1x2)+(y1y2)=k(x1 \oplus x2) + (y1 \oplus y2) = k. You are given a list of 2D points and need to find the number of pairs (i,j)(i, j) that satisfy this equation. This is a unique variation of coordinate geometry problems that relies on bitwise properties.

Why is this asked in interviews?

Google uses the "Count Pairs of Points With Distance k coding problem" to test a candidate's mastery of the XOR operator and the "Hash Table interview pattern." It requires recognizing that because kk is usually small, you can iterate through all possible ways to split kk into two components, k1k1 and k2k2, such that k1+k2=kk1 + k2 = k. It evaluates "Bit Manipulation interview pattern" skills.

Algorithmic pattern used

This problem follows the Complement Search with XOR pattern.

  1. Split k: The equation is (x1x2)=k1(x1 \oplus x2) = k1 and (y1y2)=k2(y1 \oplus y2) = k2, where k1+k2=kk1 + k2 = k.
  2. XOR Property: If x1x2=k1x1 \oplus x2 = k1, then x2=x1k1x2 = x1 \oplus k1.
  3. Implementation:
    • Iterate through the points and store their frequencies in a hash map.
    • For each point (x,y)(x, y), iterate through all possible k1k1 from 00 to kk.
    • Calculate targetX=xk1targetX = x \oplus k1 and targetY=y(kk1)targetY = y \oplus (k - k1).
    • Check the map for the count of (targetX,targetY)(targetX, targetY) and add to the result.
  4. Deduplication: Use a single pass to count and then add the current point to the map to handle pairs correctly.

Example explanation

Points: [[1, 2], [4, 2]], k=5k=5.

  • Point [1, 2]. k1k1 can be 0 to 5.
  • Let k1=5k1=5. targetX=15=4targetX = 1 \oplus 5 = 4. targetY=2(55)=2targetY = 2 \oplus (5 - 5) = 2.
  • Point [4, 2] exists! Pair found. Total pairs: 1.

Common mistakes candidates make

  • Misunderstanding XOR Distance: Trying to use Euclidean or Manhattan distance logic.
  • Complexity: Attempting O(N2)O(N^2) to check every pair. The map-based approach is O(NimesK)O(N imes K).
  • Iterating too much: Forgetting that k1k1 can only be between 00 and kk.

Interview preparation tip

Whenever a problem involves AB=CA \oplus B = C, remember that AC=BA \oplus C = B. This property is the key to transforming a search for a pair into a search for a specific target value in a hash map.

Similar Questions