• Time:O(n^2)
• Space:O(n)

## C++

``````class Solution {
public:
int numberOfBoomerangs(vector<vector<int>>& points) {
int ans = 0;

for (const auto& p : points) {
unordered_map<int, int> distCount;
for (const auto& q : points) {
const int dist = getDist(p, q);
++distCount[dist];
}
for (const auto& [_, freq] : distCount)
ans += freq * (freq - 1);  // C(freq, 2)
}

return ans;
}

private:
int getDist(const vector<int>& p, const vector<int>& q) {
return pow(p[0] - q[0], 2) + pow(p[1] - q[1], 2);
}
};
``````

## JAVA

``````class Solution {
public int numberOfBoomerangs(int[][] points) {
int ans = 0;

for (int[] p : points) {
Map<Integer, Integer> distCount = new HashMap<>();
for (int[] q : points) {
final int dist = (int) getDist(p, q);
distCount.put(dist, distCount.getOrDefault(dist, 0) + 1);
}
for (final int freq : distCount.values())
ans += freq * (freq - 1); // C(freq, 2)
}

return ans;
}

private double getDist(int[] p, int[] q) {
return Math.pow(p[0] - q[0], 2) + Math.pow(p[1] - q[1], 2);
}
}
``````

## Python

``````class Solution:
def numberOfBoomerangs(self, points: List[List[int]]) -> int:
ans = 0

for x1, y1 in points:
count = defaultdict(int)
for x2, y2 in points:
ans += 2 * count[(x1 - x2)**2 + (y1 - y2)**2]
count[(x1 - x2)**2 + (y1 - y2)**2] += 1

return ans
``````