Detect Squares (LeetCode 2013): Solution and Explanation

Medium
Design
Hash Table
Counting

Design a structure that receives points one at a time, duplicates allowed, and answers queries. For a query point, count how many ways you can pick three stored points that form, with the query, an axis-aligned square of positive area.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A naive count would try every triple of stored points, which is cubic and pointless. Fix the query point and think about what determines a square. An axis-aligned square is pinned down completely by two diagonal corners. If the query is (px, py) and the opposite corner is (x, y), the other two corners must be (x, py) and (px, y), and the shape is a square only when the horizontal and vertical distances are equal.

So for each stored point, check whether it can serve as the diagonal corner: abs(x - px) == abs(y - py) and x != px so the area is positive. If it can, the number of squares it contributes is the product of the counts of the three needed points, because duplicates count as different points and any copy of each corner can be chosen.

That makes the data structure simple: a hash map from point to how many times it was added. Adding is a constant-time increment. Counting iterates over the distinct stored points once and does three dictionary lookups for each. The code iterates over a snapshot of the keys and uses .get for the side corners, so reading a missing corner never inserts a zero entry into the map while it is being scanned.

Approach: Hash map of counts with diagonal enumeration

  1. Store a defaultdict(int) mapping each point tuple to its count.
  2. add(point) increments the count for that tuple.
  3. count(point) unpacks (px, py) and starts result = 0.
  4. For each stored (x, y), skip it unless abs(x - px) == abs(y - py) and x != px.
  5. Otherwise add points[(x, y)] * points.get((x, py), 0) * points.get((px, y), 0) to the result.
  6. Return result.

Step-by-step example

add [3,10], add [11,2], add [3,2], count [11,10], then add [11,2], count [11,10]
  1. After three adds the map is {(3,10): 1, (11,2): 1, (3,2): 1}.
  2. Query (11, 10): (3,10) has distance 8 in x but 0 in y, so it is skipped. (11,2) has the same x as the query, so it is skipped.
  3. (3,2) has distance 8 in both directions, so it is a diagonal corner. The side corners are (3,10) and (11,2), each with count 1, giving 1 × 1 × 1 = 1.
  4. Adding [11,2] again makes its count 2.
  5. The same query now gives 1 × 1 × 2 = 2, because either copy of (11,2) completes the square.

Code: Python, Java, C++

1class DetectSquares:
2    def __init__(self):
3        self.points = defaultdict(int)
4
5    def add(self, point: List[int]) -> None:
6        self.points[tuple(point)] += 1
7
8    def count(self, point: List[int]) -> int:
9        px, py = point
10        result = 0
11
12        # Snapshot keys: defaultdict reads via [] mutate the dict mid-iteration.
13        for (x, y) in list(self.points.keys()):
14            if abs(x - px) != abs(y - py) or x == px:
15                continue
16            cnt = self.points[(x, y)]
17            result += cnt * self.points.get((x, py), 0) * self.points.get((px, y), 0)
18
19        return result

Time and space complexity

Time

O(1) add, O(P) count

add is a single hash map update. count scans the P distinct stored points once and does constant work per point.

Space

O(P)

The map holds one entry per distinct point added.

Other approaches

Scan by x column (time O(1) add, O(k) count for k points in the column, space O(P))

Keep counts per point plus a map from x to the y values seen. For a query, only look at points sharing the query's x, use each one's y to get the side length, and check both squares to the left and right. Faster when columns are sparse.

Brute force over stored point lists (time O(1) add, O(N³) count, space O(N))

Keep every added point in a list and test all triples for each query. Correct but cubic and impractical.

Common mistakes

  • Forgetting the x != px check. A stored point equal to the query has zero distance in both directions, which would count degenerate squares of area zero.
  • Using defaultdict indexing for the side corners while iterating the same map. That inserts new keys mid-iteration and raises an error, which is why the code snapshots keys and uses .get.
  • Counting each square once instead of multiplying counts. Duplicate points are distinct, so the product of the three counts is required.
  • Checking only one diagonal direction. Using the absolute difference covers squares in all four quadrants around the query.

Frequently asked questions

How do you count squares in Detect Squares?

Treat every stored point as the corner diagonal to the query. If its x and y distances are equal and nonzero, the other two corners are fixed, and the contribution is the product of the three points' counts.

Why do duplicate points multiply the count?

Each copy is a different point, so any copy of each needed corner can be chosen. Choosing independently for three corners means multiplying their counts.

What is the time complexity of Detect Squares?

Adding is O(1). Counting is O(P), where P is the number of distinct stored points, because each is checked once with constant-time lookups.

Why must x != px?

If the diagonal corner had the same x as the query, the side length would be zero, which describes a degenerate square with no area.