#447
Number of Boomerangs
MediumArrayHash TableMathHash 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 count distances from each anchor point to all other points. This allows us to quickly find how many points are at the same distance, significantly reducing the number of checks needed.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a count variable to zero.
- 2Step 2: For each point, use a hashmap to store the frequency of distances to all other points.
- 3Step 3: For each distance in the hashmap, if there are 'k' points at that distance, add k * (k - 1) to the count (as each pair can form a boomerang).
- 4Step 4: Return the total count.
solution.py11 lines
1def numberOfBoomerangs(points):
2 count = 0
3 for p in points:
4 distance_count = {}
5 for q in points:
6 if p != q:
7 dist = (p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2
8 distance_count[dist] = distance_count.get(dist, 0) + 1
9 for k in distance_count.values():
10 count += k * (k - 1)
11 return countℹ
Complexity note: The time complexity remains O(n²) due to the nested loops, but we optimize the distance checks using a hashmap. The space complexity is O(n) for storing distances in the hashmap.
- 1Using a hashmap to count occurrences of distances can significantly reduce the number of checks needed.
- 2The order of points matters in boomerangs, so we must account for permutations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.