Detect Squares
Design a data structure DetectSquares that streams in 2D points. add([x, y]) inserts a point (duplicates allowed). count([x, y]) returns the number of ways to pick three points already added that, together with the query point, form an axis-aligned square with positive area. Points chosen may repeat if they were added multiple times, and counts multiply accordingly.
Open official problem prompt ↗Answer, on demand, how many axis-aligned squares of positive area a query point can form with three previously added points.
Picture a pegboard where you keep tallies of how many pegs sit at each hole. To count squares through a chosen hole, you look for pegs sitting on a perfect 45-degree diagonal from it; each such peg fixes the opposite two holes, and you multiply how many pegs occupy all three.
- Input
- add([3,10]); add([11,2]); add([3,2]); count([11,10])
- Output
- 1
- Why
- The query (11,10) with the diagonal point (3,2) needs corners (11,2) and (3,10); all three exist once, forming exactly one axis-aligned square of side 8.
point[0], point[1] in [0, 1000]At most 3000 total calls to add and countA valid square must have positive area (side length > 0)