SDE & MLE Prep

2013. Detect Squares

Problem

Design DetectSquares: add(point) records a point (duplicates allowed), and count(point) returns how many ways you can pick three recorded points that form, together with the query point, an axis-aligned square of positive area.

Example: add [3,10], [11,2], [3,2] → count([11,10]) = 1; count([14,8]) = 0

Constraints: coordinates ≤ 1000; up to 3000 calls.

Count points. For a query (x, y), each stored point (px, py) with |px − x| = |py − y| ≠ 0 is a diagonal corner; the square count is cnt[diag] · cnt[(x, py)] · cnt[(px, y)].

(x,py) ---- (px,py)      query (x,y), diagonal (px,py)
  |            |         need the other two corners
(x,y)  ---- (px,y)

Complexity: add O(1), count O(#distinct points).

class DetectSquares:
    def __init__(self):
        self.cnt = Counter()

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

    def count(self, point: List[int]) -> int:
        x, y = point
        total = 0
        for (px, py), c in list(self.cnt.items()):
            if abs(px - x) != abs(py - y) or px == x:
                continue
            total += c * self.cnt[(x, py)] * self.cnt[(px, y)]
        return total