You get points, a list of n different points on a flat plane, each written as [x, y]. A boomerang is an ordered triple of points (i, j, k) where i is exactly as far from j as it is from k.
Order matters: (i, j, k) and (i, k, j) are two different boomerangs. Return how many boomerangs there are.
Example 1
Input: points = [[0,0], [2,0], [1,1]] Output: 2 Why: [0,0] and [2,0] are equally far from [1,1]
2 more examples and the constraints
Example 2
Input: points = [[3,1], [3,4], [3,7], [0,4]] Output: 8 Why: 6 around [3,4], 2 around [0,4]
Example 3
Input: points = [[5,-2]] Output: 0 Why: a boomerang needs three points
Constraints
- 1 ≤ n ≤ 500
- −10,000 ≤ x, y ≤ 10,000
- No two points are the same
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check every tripleO(n³)
- Count distances per anchorO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 500 points | Verdict |
|---|---|---|---|
| Check every triple | O(n³) | Mention it, then move on | |
| Count distances per anchor | O(n²) | Best; one map per anchor |
n = number of points.
Edge cases to test
- One or two points. No triple exists, so return 0.
- No equal distances. [[0,0], [1,0], [3,0], [7,0]] has every distance different from every anchor: 0.
- Many at one distance. Four points on a circle around an anchor give 4 × 3 = 12 boomerangs for that anchor alone.
- Far-apart points. Squared distances reach 800,000,000, which still fits in a 32-bit integer.
Common mistakes
- Counting each pair once instead of twice; the order of j and k matters.
- Using real distances with a square root, which brings in rounding errors.
- Keeping one map across all anchors, so distances from different anchors get mixed.
How to talk through it
- 1Clarify. Does order matter? Are points distinct? How large can the coordinates be?
- 2Give the brute force. Every triple, O(n³); 125 million checks for 500 points.
- 3Fix the middle. For one anchor, only the distance to each other point matters; group by it.
- 4Code the counting. Use squared distances as map keys and add 2 × the earlier count.
- 5Test out loud. Run Example 1 by hand, then a single point and a unit square (8).
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?