Number of Boomerangs — LeetCode 447 Python Solution

MediumArrayHash TableMath
Problem
#447
Reading time
2 min

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

Python
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 << 1

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview