Number of Boomerangs — LeetCode 447 Python Solution
- Problem
- #447
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The 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).
Example
- Input
- points = [[0,0],[1,0],[2,0]]
- Output
- 2
- Explanation
- The two boomerangs are [[1,0],[0,0],[2,0]] and [[1,0],[2,0],[0,0]].
Python solution
class Solution:
def numberOfBoomerangs(self, points: List[List[int]]) -> int:
ans = 0
for p1 in points:
cnt = Counter()
for p2 in points:
d = dist(p1, p2)
ans += cnt[d]
cnt[d] += 1
return ans << 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n), where n is the length of the array `points` auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 447. Number of Boomerangs is filed here because LeetCode tags it Math, which is the vocabulary this hub collects.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 447. Number of Boomerangs?
- LeetCode 447. Number of Boomerangs is rated Medium on LeetCode.
- What is the time complexity of LeetCode 447. Number of Boomerangs?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 447. Number of Boomerangs?
- The Python solution on this page uses O(n), where n is the length of the array `points` auxiliary space.
- What topics does LeetCode 447. Number of Boomerangs cover?
- LeetCode 447. Number of Boomerangs is tagged Array, Hash Table and Math on LeetCode.