Number of Boomerangs - Problem
Number of Boomerangs
Imagine you have
A boomerang is defined as a tuple of three points
• The distance from point
• Point
• The order matters -
Return the total number of boomerangs that can be formed from the given points.
Example: If points
Imagine you have
n distinct points scattered across a 2D plane, where each point is represented as points[i] = [xi, yi]. Your task is to find all possible boomerangs that can be formed from these points.A boomerang is defined as a tuple of three points
(i, j, k) where:• The distance from point
i to point j equals the distance from point i to point k• Point
i acts as the pivot or center of the boomerang• The order matters -
(i, j, k) and (i, k, j) are considered different boomerangsReturn the total number of boomerangs that can be formed from the given points.
Example: If points
[0,0], [1,0], and [0,1] are given, point [0,0] can be the pivot with equal distances to the other two points, forming 2 boomerangs: (0,1,2) and (0,2,1). Input & Output
example_1.py — Basic case
$
Input:
points = [[0,0],[1,0],[0,1]]
›
Output:
2
💡 Note:
Point [0,0] can form 2 boomerangs: (0,1,2) and (0,2,1) since distance from [0,0] to [1,0] equals distance from [0,0] to [0,1] (both are 1 unit).
example_2.py — Single point
$
Input:
points = [[1,1]]
›
Output:
0
💡 Note:
Cannot form any boomerang with only one point since we need exactly three points for a boomerang tuple.
example_3.py — Multiple equidistant points
$
Input:
points = [[0,0],[1,0],[-1,0],[0,1],[0,-1]]
›
Output:
20
💡 Note:
Point [0,0] has 4 other points all at distance 1 from it. This gives us 4×(4-1) = 12 boomerangs. Each of the other 4 points contributes 2×(2-1) = 2 boomerangs each, totaling 12 + 4×2 = 20.
Constraints
- n == points.length
- 1 ≤ n ≤ 500
- points[i].length == 2
- -104 ≤ xi, yi ≤ 104
- All the points are unique
Visualization
Tap to expand
Understanding the Visualization
1
Choose Your Position
Pick any point as your starting position (pivot point)
2
Measure All Distances
Use your compass to measure distance to every other point
3
Group by Distance
Group points that are exactly the same distance away
4
Count Boomerang Patterns
For each group of k points: k×(k-1) boomerang patterns
5
Try Next Position
Move to next point and repeat the process
Key Takeaway
🎯 Key Insight: The hash map approach transforms an O(n³) brute force solution into an elegant O(n²) algorithm by recognizing that if k points are equidistant from a pivot, they automatically form k×(k-1) boomerangs due to the ordered nature of the tuples.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code