Problem overview
The class DetectSquares stores points on a grid, each an int[] [x, y], and answers counting questions:
add(int[] point)stores a point. Adding the same point twice stores it twice.count(int[] point)returns the number of squares that havepointas one corner and stored points as the other three. The sides are horizontal and vertical and at least 1 long. Each copy of a stored point is a separate corner, so copies multiply the number of squares.countdoesn't store its point.
Coordinates are from 0 to 1,000 and there are at most 5,000 calls.
Take the points (2,1), (6,5) and (2,5). Asking about (6,1) finds one square with those four corners. Asking about (4,3), the middle of that square, returns 0. After adding a second copy of (2,5), asking about (6,1) returns 2: each copy forms its own square.
Approach: pick the opposite corner, look up the other two
If the query point is (x, y), one of the stored points could be the corner diagonally across from it, at (px, py). A square with that diagonal has exactly two other corners, (px, y) and (x, py). So for each stored point as the candidate opposite corner, check two things:
- It lies on a true diagonal:
px != x(so the side is at least 1) andMath.abs(px - x) == Math.abs(py - y)(the horizontal and vertical distances are equal). - The other two corners exist: look up their counts.
The number of squares for that diagonal is the product of the three counts, because any copy of each corner can be chosen. Adding up over all candidates gives the answer.
This takes one pass over the different stored points per count, so it is O(n) for n distinct points, instead of testing every triple of points. The loop goes through each different point once, even if it was added many times, because the multiplication by its count covers the copies.
Step by step
- Two fields.
countsis aMap<String, Integer>from a point to how many times it was added, andpointsis aList<int[]>holding each different point once. - Build a key in
add.point[0] + "," + point[1]gives a string such as"2,5". Two arrays with the same numbers are still two different objects and don't compare equal as map keys; equal strings do. The comma keeps the numbers apart: 1 and 23 give"1,23", while 12 and 3 give"12,3". - Count it.
counts.put(key, counts.getOrDefault(key, 0) + 1).getOrDefault(key, 0)returns 0 when the key isn't in the map yet. - Remember new points. If the count of
keyis now 1, the point is new, so it goes intopoints. - Start
count. Store the query's coordinates inxandyand settotalto 0. The method only reads the fields. - Try every stored point as the opposite corner, named
p, withpxandpyfor its coordinates. - The diagonal test.
px != x && Math.abs(px - x) == Math.abs(py - y). - The other two corners.
cornersis the count of(px, y)times the count of(x, py), each looked up withgetOrDefault(..., 0). If one is missing, the product is 0. - The key line. Add the count of
(px, py)timescornerstototal. - Return
total.
The solution in Java
class DetectSquares {
Map<String, Integer> counts = new HashMap<>();
List<int[]> points = new ArrayList<>();
public void add(int[] point) {
String key = point[0] + "," + point[1];
counts.put(key, counts.getOrDefault(key, 0) + 1);
if (counts.get(key) == 1) {
points.add(point);
}
}
public int count(int[] point) {
int x = point[0], y = point[1];
int total = 0;
for (int[] p : points) {
int px = p[0], py = p[1];
if (px != x && Math.abs(px - x) == Math.abs(py - y)) {
int corners = counts.getOrDefault(px + "," + y, 0) * counts.getOrDefault(x + "," + py, 0);
total += counts.get(px + "," + py) * corners;
}
}
return total;
}
}
Java details worth knowing:
- Arrays use identity for
equalsandhashCode. AfterMap<int[], Integer> mstores a keynew int[]{1, 2}, a lookup with anothernew int[]{1, 2}returnsnull;Arrays.equalssays they match, butequalson the arrays themselves givesfalse. That is why the points are turned into strings for the map. counts.get(key) == 1compares anIntegerwith anint, so theIntegeris unboxed and the comparison is by value. Comparing twoIntegerobjects with==would compare references and is unreliable for larger numbers.- In
count,counts.get(px + "," + py)never returnsnull: every point inpointswas added, so its key is in the map. - The product of counts is an
int. The statement promises every answer fits in 32 bits.
Complexity
Time: add is O(1) on average. count is O(n) for n different points: one pass, with a few hash lookups per point. Space: O(n) for the map and the list.
Edge cases and common mistakes
- The query point is stored too. After adding (4,4) twice,
count([4,4])returns 0: the only stored point on that spot haspx == x, so it fails the first test. A square needs a side of at least 1. - A rectangle that isn't a square. In the second example, (1,0) forms a rectangle 2 wide and 3 tall with the other corners, and the distance check rejects it.
- Counting copies twice. Looping over every added copy and also multiplying by counts would overcount. Keeping each different point once in
pointsavoids that. - Dropping the comma in the key. Without a separator, (1,23) and (12,3) would both become
"123". - Storing the query.
countmust not change any field.
Testing
The first example, with calls in order, gives:
add [2,1], add [6,5], add [2,5]
count [6,1] -> 1
count [4,3] -> 0
add [2,5]
count [6,1] -> 2
With the points (1,1), (1,3), (3,1), (6,3), (6,0), (3,0) and (1,0), count([3,3]) returns 2: one square of side 2 and one of side 3. With (4,4) added twice, then (4,7) and (7,4), count([7,7]) returns 2 (one square for each copy of (4,4)) and count([4,4]) returns 0, because (7,7) was never stored.
