Number of Boomerangs - Problem

You are given n points in the plane that are all distinct, where points[i] = [xi, yi].

A boomerang is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters).

Return the number of boomerangs.

Input & Output

Example 1 — Basic Boomerangs
$ Input: points = [[0,0],[1,0],[2,0]]
Output: 2
💡 Note: Two boomerangs exist: (1,0,2) and (1,2,0). From point [1,0]: distance to [0,0] = 1, distance to [2,0] = 1 (equal distances). The other points don't have equal distances to any pair of other points.
Example 2 — Square Formation
$ Input: points = [[1,1],[2,2],[3,3]]
Output: 2
💡 Note: Points form a diagonal line. From [2,2]: distance to [1,1] = √2, distance to [3,3] = √2. So (2,1,3) and (2,3,1) are valid boomerangs.
Example 3 — No Boomerangs
$ Input: points = [[1,1]]
Output: 0
💡 Note: Only one point exists, so no boomerangs can be formed (need at least 3 points).

Constraints

  • n == points.length
  • 1 ≤ n ≤ 500
  • points[i].length == 2
  • -104 ≤ xi, yi ≤ 104
  • All the points are unique

Visualization

Tap to expand
Number of Boomerangs INPUT P0 P1 P2 0 1 2 points array: [0,0] [1,0] [2,0] i=0 i=1 i=2 All points on x-axis Distance P0-P1 = 1 Distance P1-P2 = 1 Distance P0-P2 = 2 ALGORITHM (Hash) 1 For each point i Calculate distances to all other points j, k 2 Build distance HashMap Key: squared distance Value: count of points 3 Count permutations For n points at same dist: n * (n-1) boomerangs 4 Sum all counts Add boomerangs from each center point i HashMap for P1 (center) dist=1: count=2 P0, P2 same dist Boomerangs: 2*(2-1) = 2 (P1,P0,P2) and (P1,P2,P0) P0, P2 as center: 0 each FINAL RESULT Valid Boomerangs Found: Boomerang 1: (1,0,2) P0 P1 P2 Boomerang 2: (1,2,0) P2 P1 P0 Output: 2 boomerangs OK - Verified Key Insight: A boomerang (i,j,k) requires dist(i,j) = dist(i,k). Using a HashMap to group points by their distance from center i, if n points share the same distance, we can form n*(n-1) ordered pairs (j,k). The order matters: (i,j,k) != (i,k,j). Time: O(n^2) for computing all pairwise distances. Space: O(n) for the HashMap. TutorialsPoint - Number of Boomerangs | Hash Approach
Asked in
Google 15 Amazon 12 Apple 8
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen