Detect Squares
Learn how to solve the 'Detect Squares' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
You are given a stream of points on the X-Y plane. Design a data structure that:
- Adds new points from the stream. Duplicate points are allowed and should be treated as different points.
- Given a query point, counts the number of ways to choose three points from the data structure such that the three points and the query point form an axis-aligned square with positive area.
An axis-aligned square is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and the y-axis.
Implement a function detectSquares(operations: list, arguments: list) -> list where operations are 'DetectSquares', 'add', or 'count', and arguments are the corresponding parameters. Returns a list of results (None for constructor and add).
- •point.length == 2
- •0 <= x, y <= 1000
- •At most 3000 calls in total will be made to add and count
Examples
["DetectSquares","add","add","add","count","count","add","count"], [[],[3,10],[11,2],[3,2],[11,10],[14,8],[11,2],[11,10]]
[None,None,None,None,1,0,None,2]
After adding (3,10), (11,2), (3,2): count(11,10) finds 1 square with corners (3,10),(11,10),(11,2),(3,2). count(14,8) finds 0. After adding another (11,2): count(11,10) finds 2 squares (using each copy of (11,2)).
Need a Hint?
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.