Detect Squares
MediumNeetCode 150 Math & GeometryProblem
Build a class DetectSquares that collects points on a 2D plane and answers questions about squares.
It supports these operations:
DetectSquares()creates an empty collection.add(point)adds the point[x, y]. The same point may be added many times, and each copy counts separately.count(point)takes a query point[x, y]and returns how many ways there are to pick three stored points that, together with the query point, form a square with positive area whose sides are parallel to the x and y axes.
The query point is not stored. Two ways are different if they use different copies of a repeated point.
The input is a list of calls and their arguments; the output lists what each call returns
(null for the constructor and for add).
Constraints
- 0 ≤ x, y ≤ 1000
- At most 3000 calls in total to add and count
Examples: pick one to animate
Solutions
Time: add updates a map and appends to a list. count loops once over the n stored points, with O(1) map lookups.
Space: The list holds every added point and the map holds each distinct point once.
A square is fixed by one corner and the corner opposite it. Keep a map from point to how many copies were added, and a list of every added point. For a query, treat each listed point as the opposite corner: it works only if it is as far across as it is up or down, and not the query point itself. The other two corners are then fixed, and the number of squares is the product of how many copies of each exist.