Detect Squares
Detailed guide and Python implementation for the 'Detect Squares' problem.
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 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.
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.