InterviewPrepKit

Home / Coding / Math & Geometry

Detect Squares

medium Original ↗
Solving tips
  • Fix the diagonal corner: a valid diagonal (x,y) needs abs(x-px) == abs(y-py) and x != px and y != py (positive area).
  • Once the query point and diagonal are fixed, the other two corners are forced to (px,y) and (x,py).
  • Store point multiplicities in a Counter so each corner count is an O(1) lookup, and multiply the three counts to handle duplicate points.
  • add is O(1); count iterates distinct points, so O(D) per query, O(D) space.

Problem

Design a data structure that supports two operations on a growing collection of 2-D points:

  • add(point) — add the point [x, y] to the collection. Duplicate points are allowed and each copy counts.
  • count(point) — given a query point [x, y], return how many axis-aligned squares of positive area can be formed using the query point as one corner together with three points already in the collection. A square with a corner appearing k times contributes k to the tally through that corner.

An axis-aligned square has sides parallel to the x- and y-axes.

Examples

Consider the call sequence:

  • add([3, 10]), add([11, 2]), add([3, 2])
  • count([11, 10])1 — the four corners (11,10), (3,10), (11,2), (3,2) form one square.
  • count([14, 8])0 — no square can be completed.
  • add([11, 2]) (a second copy), then count([11, 10])2 — the corner (11,2) now exists twice, doubling the count.

Constraints

  • 0 <= x, y <= 1000
  • At most 3000 calls total to add and count.

Think about it first

Hint 1 For an axis-aligned square, pick the corner diagonally opposite the query point. That diagonal corner `(px, py)` must satisfy `|px - x| == |py - y|` (equal horizontal and vertical distance) and be off both axes of the query point.
Hint 2 Once you fix the query point `(x, y)` and a diagonal point `(px, py)`, the other two corners are forced: `(x, py)` and `(px, y)`. The number of squares through that diagonal is the product of how many times each of the three other corners appears.
Hint 3 Keep a count (a hash map from point to multiplicity). For a query, iterate over the *distinct* stored points as candidate diagonals; for each valid one, multiply the three corner counts and sum. Multiplicities let repeated points contribute multiple squares.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.