Leetcode 2139 Solution

This article provides solution to leetcode question 2139 (detect-squares)

https://leetcode.com/problems/detect-squares

Solution

class DetectSquares:

    def __init__(self):
        self.points = collections.defaultdict(int)

    def add(self, point: List[int]) -> None:
        self.points[(point[0], point[1])] += 1

    def count(self, point: List[int]) -> int:
        ans = 0
        x1, y1 = point
        for point2, cnt in self.points.items():
            x2, y2 = point2

            if x1 == x2 or y1 == y2:
                continue

            if abs(x1 - x2) != abs(y1 - y2):
                continue

            ans += cnt * self.points.get((x1, y2), 0) * self.points.get((x2, y1), 0)
        return ans


# Your DetectSquares object will be instantiated and called as such:
# obj = DetectSquares()
# obj.add(point)
# param_2 = obj.count(point)