Problem Description
Given n distinct points in the plane, count the number of boomerangs. A boomerang is a tuple of points (i, j, k) such that the distance between point i and j equals the distance between point i and k. Note that the order of the tuple matters.
Key Insights
- For every point taken as the pivot i, compute the distance between i and every other point.
- Use the squared Euclidean distance to avoid dealing with floating-point numbers.
- Group points by the same distance from the pivot.
- For each group with count c, there are c * (c - 1) boomerangs since the ordering of j and k matters.
Space and Time Complexity
Time Complexity: O(n^2), as for each of the n points, we compute the distance to every other point. Space Complexity: O(n), due to the hash map used to store distances for each point.
Solution
We iterate through each point considering it as the center of boomerangs. For each center, we create a hash map (or dictionary) to count how many points are at each squared distance. Once the distances are tallied, if there are count c points at a given distance, they contribute c * (c - 1) boomerang tuples. Summing these contributions yields the final count.