15% off all plans & roadmaps Use code

See plans

Detect Squares

Updated

TL;DR: Store every added point in a list and a frequency map. For a query, treat each stored point as the diagonal corner, then multiply the counts of the two forced corners.

Problem

You receive a stream of points on the X-Y plane. Build a data structure that supports two operations:

  • Add a point from the stream. Duplicate points are allowed, and each copy counts as a separate point.
  • Count how many ways you can pick three stored points that, together with a given query point, form an axis-aligned square with positive area.

An axis-aligned square has four equal sides, and every side is parallel to the x-axis or the y-axis.

Implement the DetectSquares class:

  • DetectSquares() creates an empty data structure.
  • void add(int[] point) adds the point [x, y] to the structure.
  • int count(int[] point) returns the number of ways to form axis-aligned squares using the query point [x, y], as described above.

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: [null, null, null, null, 1, 0, null, 2]
Explanation:
DetectSquares detectSquares = new DetectSquares();
detectSquares.add([3, 10]);
detectSquares.add([11, 2]);
detectSquares.add([3, 2]);
detectSquares.count([11, 10]); // returns 1: the first, second and third points
detectSquares.count([14, 8]);  // returns 0: no square is possible
detectSquares.add([11, 2]);    // duplicates are allowed
detectSquares.count([11, 10]); // returns 2: points 1, 2, 3 or points 1, 3, 4

Constraints

  • point.length == 2
  • 0 <= x, y <= 1000
  • At most 3000 calls in total are made to add and count.

Constraints that matter

  • At most 3000 calls in total, so up to about 3000 stored points. A count that checks every triple does around 4.5 * 10^9 steps, which is far too slow.
  • A count that touches each stored point once costs about 3000 steps. Even 3000 such calls cost under 10^7 steps in total, which is fine.
  • Coordinates are between 0 and 1000, so a point packs into one integer key as x * 1001 + y. Keys never collide.
  • Duplicates are separate points, so you must store counts rather than a set. Two copies of a corner double the number of squares.
  • One count result is at most 1000 * 1000 * 1000 = 10^9 in the worst case, which fits in a 32-bit int.

View on LeetCode

Hints

Hint 1

This is a design problem with a hash map inside.

Hint 2

Keep every added point in a list.

Solution

Intuition

This is a design problem with a hash map inside. The hard part is count, because the statement says to choose three points. That wording hides a shortcut: in an axis-aligned square, two opposite corners fix the other two.

Picture a pegboard where each hole holds a count of how many points were placed there. The hash map is that pegboard, and each stored point is a peg you test against the query: you find the two holes that would complete the square with it and multiply the peg counts in those holes.

Take the query (qx, qy) and a stored point (px, py) as diagonal corners. They form a square only if |qx - px| == |qy - py| and the side is not zero. Then the remaining corners must be (qx, py) and (px, qy). You do not search for them. You look them up.

So the problem turns from "find three unknown points" into "pick one diagonal point and read two counts". A frequency map gives each count in O(1). The number of squares for that diagonal point is count(qx, py) * count(px, qy), because any copy of one corner pairs with any copy of the other.

Duplicates need one more thought. If you loop over a list that holds every added point, each copy of the diagonal point is visited on its own. That gives the diagonal multiplicity for free, and you never multiply by it explicitly.

Watch the pattern animation

Worked example

Input: commands = ["DetectSquares", "count"], params = [[], [[5, 5]]]
Output: [null, 0]
Explanation: The structure is empty when count([5, 5]) runs, so no three stored points exist and the answer is 0. The dry runs below also replay the add and count calls from the problem statement, so you can see a non-zero answer.

Approach 1: Brute force over triples

Keep every added point in a list. For a query, try every group of three stored points and test whether the four points form an axis-aligned square.

The test is the only subtle part. Pick one of the three points as the diagonal partner of the query, check the side rule, and see whether the other two points are exactly the two forced corners.

Steps

  1. Store each added point in a list.
  2. In count, loop over every index triple i < j < k.
  3. For each triple, try each of the three points as the diagonal partner of the query.
  4. The partner (dx, dy) must satisfy dx != qx and |dx - qx| == |dy - qy|.
  5. The other two points must be (qx, dy) and (dx, qy) in either order.
  6. Add 1 to the answer for every triple that passes, then return the total.

Dry run

On the page example the list is empty, so there are no triples and count([5, 5]) returns 0.

On the statement's first count the list holds (3, 10), (11, 2), (3, 2) and the query is (11, 10). There is one triple. Trying (3, 2) as the partner gives dx = 3, |3 - 11| = 8 and |2 - 10| = 8, so the side rule holds.

The forced corners are (11, 2) and (3, 10), and the other two points are exactly those. The answer is 1.

Complexity

TimeO(n^3) per count, O(1) per add
SpaceO(n)

Here n is the number of points added so far. count visits n * (n - 1) * (n - 2) / 6 triples and each test is constant work, which is O(n^3). With n near 3000 that is about 4.5 * 10^9 tests for one call. The list stores one entry per added point, so space is O(n).

PythonTested in our runner

from typing import List, Optional

class DetectSquares:
    def __init__(self):
        self.points = []

    def add(self, point: List[int]) -> None:
        self.points.append((point[0], point[1]))

    def count(self, point: List[int]) -> int:
        qx, qy = point
        n = len(self.points)
        res = 0
        for i in range(n):
            for j in range(i + 1, n):
                for k in range(j + 1, n):
                    trio = (self.points[i], self.points[j], self.points[k])
                    if self._is_square(qx, qy, trio):
                        res += 1
        return res

    def _is_square(self, qx, qy, trio):
        for d in range(3):
            dx, dy = trio[d]
            o1 = trio[(d + 1) % 3]
            o2 = trio[(d + 2) % 3]
            if dx != qx and abs(dx - qx) == abs(dy - qy):
                a = (qx, dy)
                b = (dx, qy)
                if (o1 == a and o2 == b) or (o1 == b and o2 == a):
                    return True
        return False
Design (General/Specific) pattern infographic for Detect Squares

Solution pattern

Design (General/Specific)

Part of Design Patterns

Approach 2: Hash map plus diagonal scanOptimalDesign (General/Specific)

What's slow: the brute force searches for three unknown points, so it pays for every triple. Almost all of those triples fail the first side check.

The insight that fixes it: one stored point plus the query already decides the whole square. Scan the stored points once. For each point that sits on a valid diagonal from the query, read the counts of the two forced corners from a frequency map and multiply them.

Keep two structures. A list holds every added point, so duplicate copies of a diagonal point are each visited. A map from point to count answers corner lookups in O(1).

Why it is correct. Every square that has the query as one corner has exactly one opposite corner, so it is found by exactly one stored point. Once that diagonal point is fixed, the other two corners are forced, so no square is missed or counted twice. Each copy of a stored point is its own list entry, so duplicate copies multiply correctly. Points that fail the side-length check cannot be opposite corners of any square with the query, so skipping them loses nothing.

Steps

  1. Create an empty list points and an empty map counts from point to frequency.
  2. In add, append the point to the list and increase its count in the map by 1.
  3. In count, read (qx, qy) and set ans = 0.
  4. For each (px, py) in the list, skip it unless |px - qx| == |py - qy| and px != qx.
  5. Look up counts[(qx, py)] and counts[(px, qy)], treating a missing key as 0.
  6. Add the product of those two counts to ans.
  7. Return ans after the scan.

Dry run

Trace the page example first. count([5, 5]) runs on an empty list. The loop body never runs, so the answer is 0 and the output is [null, 0].

Now replay the statement's calls to see a non-zero result. Counts are keyed by (x, y).

StepActionList of pointsCounts or workResult
1add (3, 10)(3,10)counts[(3,10)] = 1null
2add (11, 2)(3,10), (11,2)counts[(11,2)] = 1null
3add (3, 2)(3,10), (11,2), (3,2)counts[(3,2)] = 1null
4count (11, 10), point (3,10)samedx = 8, dy = 0, not equal, skipans = 0
5point (11,2)samedx = 0, skipans = 0
6point (3,2)samedx = 8, dy = 8. Corners (11,2) and (3,10) have counts 1 and 1ans = 1
7count (14, 8)same(3,10): dx 11, dy 2. (11,2): dx 3, dy 6. (3,2): dx 11, dy 6. None match0
8add (11, 2)(3,10), (11,2), (3,2), (11,2)counts[(11,2)] = 2null
9count (11, 10)same(3,10) skip, both (11,2) skip because dx = 0. (3,2) gives counts[(11,2)] * counts[(3,10)] = 2 * 12

The outputs for steps 4, 7 and 9 are 1, 0 and 2, matching the statement.

Complexity

TimeO(1) per add, O(n) per count
SpaceO(n)

Here n is the number of points added so far. add does one append and one map update, so it is O(1) on average. count makes one pass over the list, and each iteration does an absolute value check and two map lookups, so it is O(n). The list and the map each hold at most n entries, so space is O(n). With at most 3000 calls the whole run stays under about 10^7 steps.

PythonTested in our runner

from typing import List, Optional
from collections import defaultdict

class DetectSquares:
    def __init__(self):
        self.counts = defaultdict(int)  # (x, y) -> how many copies
        self.points = []                # every added point, duplicates included

    def add(self, point: List[int]) -> None:
        x, y = point
        self.counts[(x, y)] += 1
        self.points.append((x, y))

    def count(self, point: List[int]) -> int:
        qx, qy = point
        ans = 0
        for px, py in self.points:
            # (px, py) must be a diagonal corner with positive side
            if px == qx or abs(px - qx) != abs(py - qy):
                continue
            # forced corners: (qx, py) and (px, qy)
            ans += self.counts.get((qx, py), 0) * self.counts.get((px, qy), 0)
        return ans

Common mistakes

  • Using a set or a map without a list, such as if (x, y) not in seen before adding. Duplicates are separate points, so keep a frequency map for the corners and a list (or a count multiplier) for the diagonal point.
  • Dropping the px == qx check. A stored point with the same x and y as the query gives |dx| == |dy| == 0, which counts a zero-area square. Skip any point with px == qx.
  • Comparing qx - px == qy - py without absolute values. That only finds squares in one direction. Use abs(qx - px) == abs(qy - py) so squares above, below, left and right all count.
  • Multiplying by the diagonal point's own count, as in counts[(px, py)] * counts[(qx, py)] * counts[(px, qy)] while also looping over the list with duplicates. Each copy is already visited separately, so this counts the copies twice. Multiply only the two corner counts.
  • Counting rectangles by checking only that corners exist, without the |dx| == |dy| test. A rectangle with unequal sides is not a square. Test the side equality first.
  • Looking up a missing key and getting an error or inserting an entry, such as counts[(qx, py)] on a plain Python dict. Use .get(key, 0), or a defaultdict that you do not mind growing. In Java and C#, use the default-value form of the lookup.

Edge cases

  • count on an empty structure returns 0. This is the page example.
  • The query equals a stored point, such as query (5, 5) with (5, 5) stored. The side is zero, so skip it. The answer stays 0.
  • Two copies of one corner and one copy of the other, with the diagonal point present once. The answer is 2 * 1 = 2.
  • The diagonal point is stored twice and each corner once. The answer is 2, because the list visits both copies.
  • Points that share only x or only y with the query, such as (3, 10) against query (11, 10). They fail |dx| == |dy| or have dx = 0, so they add nothing.
  • Coordinates at the limits, such as query (0, 0) with points (1000, 1000), (0, 1000) and (1000, 0). The answer is 1, and the key x * 1001 + y stays unique.

Follow-ups interviewers ask

Can you make count faster than a scan over all stored points?
Yes. Group counts by x, so cols[x] maps y to a frequency. For a query, loop over the y values in cols[qx], which are the points directly above and below the query. For each y with side d = y - qy and d != 0, check the column qx + d and the column qx - d. Multiply the three counts. The work is bounded by the distinct y values in one column, at most 1001, instead of the number of added points.
What if coordinates were huge and a 2D array was impossible?
Use a hash map keyed by the pair or by a packed integer. Packing needs a multiplier larger than the maximum coordinate, and 64-bit integers if the product could overflow. The approach and the complexity do not change. Only memory per entry changes.
What if squares could be rotated, not just axis-aligned?
Two diagonal corners no longer fix the others by a simple swap. For a diagonal pair you compute the other two corners with the midpoint and a 90 degree rotation, and they must land on integer points. You can then look them up in the same frequency map. The scan stays O(n) per count, but you need care with integer midpoints and a doubled-coordinate trick to avoid fractions.

Detect Squares FAQ

What is the time complexity of Detect Squares?

add is O(1) on average. count is O(n), where n is the number of points added so far, because it scans the list once and does two O(1) lookups per point. The brute force over triples is O(n^3) per count.

Why use a hash map for Detect Squares?

After you pick a diagonal point, the other two corners are fixed, so you only need to know how many copies of each exist. A hash map from point to count answers that in O(1). Without it you would scan the list again for every corner.

Why do the two corner counts multiply?

Any copy of the first corner can pair with any copy of the second corner. With a copies of one and b copies of the other, there are a * b distinct choices of three points for that diagonal point.

Can Detect Squares be solved in O(1) extra space?

No. The structure must remember every added point, and duplicates change the answer, so you need at least a count per distinct point. A fixed 1001 by 1001 array is constant in n but still uses about a million integers. The list of points is the part that grows with n.

How do I solve LeetCode 2013 in Python?

Use a defaultdict(int) for point counts and a list of points. In count, loop over the list, skip points where px == qx or the absolute differences differ, and add the product of the two corner counts. Use .get(key, 0) for the lookups so the map does not grow during a query.

Why must the query point be treated differently from stored points?

The query is never stored, so a call to count does not change the structure. Only the three other corners come from stored points. The query only supplies the fixed corner from which you test each diagonal.

Asked at

See which companies ask this — Pro

Practise it