The problem, Number of Boomerangs (LeetCode 447), is as follows:
Given n
points in the plane that are all pairwise distinct, 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).
You need to return the number of boomerangs.
Input: [[0,0],[1,0],[2,0]]
Output: 2
Explanation: The two boomerangs are [[0,0],[1,0],[2,0]] and [[2,0],[1,0],[0,0]]
0
because it’s not possible to form a boomerang with fewer than 3 points.def numberOfBoomerangs(points):
from collections import defaultdict
def get_distance(p1, p2):
return (p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2
boomerangs_count = 0
for i in range(len(points)):
distance_map = defaultdict(int)
for j in range(len(points)):
if i == j:
continue
distance = get_distance(points[i], points[j])
distance_map[distance] += 1
for distance, count in distance_map.items():
if count > 1:
boomerangs_count += count * (count - 1)
return boomerangs_count
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?