Top 150 InterviewEasy

Detect Squares

Detailed guide and Python implementation for the 'Detect Squares' problem.

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?
Consider using Math & Geometry-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.