Back to Practice Dashboard
Top 150 InterviewEasy

Detect Squares

Learn how to solve the 'Detect Squares' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Easy

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).

Constraints
  • point.length == 2
  • 0 <= x, y <= 1000
  • At most 3000 calls in total will be made to add and count

Examples

Example 1
Input
["DetectSquares","add","add","add","count","count","add","count"], [[],[3,10],[11,2],[3,2],[11,10],[14,8],[11,2],[11,10]]
Output
[None,None,None,None,1,0,None,2]
Explanation

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?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
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.

Open in Editor