#2857
Count Pairs of Points With Distance k
MediumArrayHash TableBit ManipulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a HashMap to store the frequency of possible distances, allowing us to find pairs more efficiently. This reduces the need for nested loops and speeds up the process significantly.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a HashMap to keep track of the frequency of points based on their coordinates.
- 2Step 2: Iterate through each point and calculate the required coordinates for the other point that would yield the distance k.
- 3Step 3: For each point, determine how many times the required coordinates have been seen before using the HashMap.
- 4Step 4: Update the HashMap with the current point's coordinates after checking.
solution.py15 lines
1# Full working Python code
2
3def countPairs(coordinates, k):
4 from collections import defaultdict
5 count = 0
6 freq_map = defaultdict(int)
7 for x1, y1 in coordinates:
8 for x2 in range(0, 2**20): # 20 bits for 10^6
9 y2 = (k - (x1 ^ x2))
10 count += freq_map[(x2, y2)]
11 freq_map[(x1, y1)] += 1
12 return count
13
14# Example usage
15print(countPairs([[1,2],[4,2],[1,3],[5,2]], 5))ℹ
Complexity note: The time complexity is O(n) because we only iterate through the list of coordinates once, and the space complexity is O(n) due to the storage of point frequencies in the HashMap.
- 1Using XOR allows for efficient distance calculations based on bit manipulation.
- 2HashMaps can significantly reduce the time complexity by storing previously seen coordinates.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.