Problem Statement
(Source) 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).
Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive).
Example:
Input: [[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]]
Solution
Tags: Hash Table
, Math
.
class Solution(object):
def numberOfBoomerangs(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
m, n = {}, len(points)
for i in xrange(n - 1):
for j in xrange(i + 1, n):
if j != i:
d = pow(points[i][0] - points[j][0], 2) + pow(points[i][1] - points[j][1], 2)
dist_from_i = m.setdefault(i, {})
dist_from_i[d] = dist_from_i.get(d, 0) + 1
dist_from_j = m.setdefault(j, {})
dist_from_j[d] = dist_from_j.get(d, 0) + 1
return sum(size * (size - 1) for i in m for size in m[i].values() if size > 1)
Complexity Analysis:
- Time Complexity: O(n2) .
- Space Complexity: O(n2) .
TODO
To see if the proposed algorithm can be further optimised. It seems that time complexity
cannot be optimised if the process to calculating distances between all pairs of points cannot be avoided. But maybe the space complexity
can be further optimised.