LC 2013 [M] Detect Squares - ALawliet/algorithms GitHub Wiki

class DetectSquares:

    def __init__(self):
        self.ptsCount = defaultdict(int)
        self.pts = []
        

    def add(self, point: List[int]) -> None:
        self.ptsCount[tuple(point)] += 1
        self.pts.append(point)
        

    def count(self, point: List[int]) -> int:
        res = 0
        px, py = point # query point
        for x, y in self.pts: # diagonal
            if (abs(py - y) != abs(px - x)) or x == px or y == py:  # not a square if horizontal/vertical not equal or query/diagonal points match
                continue
            res += self.ptsCount[(x, py)] * self.ptsCount[(px, y)] # top left and bottom right
        return res
        


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