AAlgoLoopSpaced repetition for LeetCode
MEDIUMDesignLeetCode ↗

Detect Squares

The key idea

Keep a frequency map of every added point keyed by x,y. To count squares sharing a query point, only the two points on the SAME diagonal pin the square: scan stored points p where |p.x - x| == |p.y - y| and the gap is non-zero, then multiply the counts of the two remaining corners that the diagonal forces.

Problem

You are given a stream of points on the X-Y plane. Design an algorithm that:

- Adds new points from the stream into a data structure. Duplicate points are allowed and should be treated as different points.
- Counts the number of ways to choose three points from the data structure such that the three chosen points and a given 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 parallel to the X-axis and Y-axis.

Implement the DetectSquares class:

- DetectSquares() initializes the object.
- add(point) adds a new point point = [x, y] to the data structure.
- count(point) counts the number of ways to form axis-aligned squares with the query point point = [x, y] as described above, and returns that count.

Constraints

Examples

Input: ["DetectSquares","add","add","add","count","count","add","count"] [[],[[3,10]],[[11,2]],[[3,2]],[[11,10]],[[14,8]],[[11,2]],[[11,10]]] Output: [null,null,null,null,1,0,null,2]
Input: count([11,10]) after add [3,10],[11,2],[3,2] Output: 1
Input: count([11,10]) after add [3,10],[11,2],[3,2],[11,2] Output: 2

Complexity

Time: O(n) per count, O(1) per add Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More Design problems