Start learning free

LESSON 314 OF 314 · MATH

Detect Squares in Java: HashMap of Point Counts, O(n) per Count

Practice O(n) Read the full explanation

You get a series of calls to a class, DetectSquares. It stores points on a grid.

Each point is an array [x, y] of two integers.

Implement the class:

  • DetectSquares() starts with no points.
  • add(point) stores point. A point added twice is stored twice.
  • count(point) returns the number of squares with point as one corner and stored points as the other three.

A square has two horizontal and two vertical sides. Its sides are at least 1 long.

Each copy of a stored point is a separate corner. So copies make more squares.

count doesn't store its point.

The calls run in order on one new DetectSquares. The output lists what the count calls return, in order. The starter code spells these names the way your language does.

 

Example 1:

Input:
1. add([2, 1])
2. add([6, 5])
3. add([2, 5])
4. count([6, 1])
5. count([4, 3])
6. add([2, 5])
7. count([6, 1])
Output: 1 0 2
Explanation: Call 4 finds one square.
Its corners are (2, 1), (6, 5), (2, 5) and (6, 1).
(4, 3) is the middle of that square, not a corner.
So call 5 returns 0.
Call 6 adds a second copy of (2, 5).
Each copy makes its own square, so call 7 returns 2.

Example 2:

Input:
1. add([1, 1])
2. add([1, 3])
3. add([3, 1])
4. add([6, 3])
5. add([6, 0])
6. add([3, 0])
7. add([1, 0])
8. count([3, 3])
Output: 2
Explanation: (3, 3) completes two squares of different sizes.
One has side 2, with (1, 1), (1, 3) and (3, 1).
The other has side 3, with (6, 3), (6, 0) and (3, 0).
(1, 0) makes a rectangle with (1, 3), (3, 0) and (3, 3).
It is 2 wide and 3 tall, so it doesn't count.

Example 3:

Input:
1. add([4, 4])
2. add([4, 4])
3. count([4, 4])
4. add([4, 7])
5. add([7, 4])
6. count([7, 7])
7. count([4, 4])
Output: 0 2 0
Explanation: Call 3 returns 0.
A square needs sides at least 1 long.
Call 6 returns 2.
(7, 7) completes a square with (4, 7), (7, 4) and either copy of (4, 4).
Call 7 returns 0, because (7, 7) was never stored.

 

Constraints:

  • Each x and y is a whole number from 0 to 1,000.
  • At most 5,000 calls in total.
  • Every answer of count fits in a 32-bit signed integer.

Note:

count should run in O(n) time, where n is the number of different points stored.

STEP 1 OF 13
    Ctrl + Enter to check

    JAVA · MATH

    Detect Squares in Java, explained

    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 have point as 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. count doesn'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:

    1. It lies on a true diagonal: px != x (so the side is at least 1) and Math.abs(px - x) == Math.abs(py - y) (the horizontal and vertical distances are equal).
    2. 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

    1. Two fields. counts is a Map<String, Integer> from a point to how many times it was added, and points is a List<int[]> holding each different point once.
    2. 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".
    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.
    4. Remember new points. If the count of key is now 1, the point is new, so it goes into points.
    5. Start count. Store the query's coordinates in x and y and set total to 0. The method only reads the fields.
    6. Try every stored point as the opposite corner, named p, with px and py for its coordinates.
    7. The diagonal test. px != x && Math.abs(px - x) == Math.abs(py - y).
    8. The other two corners. corners is the count of (px, y) times the count of (x, py), each looked up with getOrDefault(..., 0). If one is missing, the product is 0.
    9. The key line. Add the count of (px, py) times corners to total.
    10. 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 equals and hashCode. After Map<int[], Integer> m stores a key new int[]{1, 2}, a lookup with another new int[]{1, 2} returns null; Arrays.equals says they match, but equals on the arrays themselves gives false. That is why the points are turned into strings for the map.
    • counts.get(key) == 1 compares an Integer with an int, so the Integer is unboxed and the comparison is by value. Comparing two Integer objects with == would compare references and is unreliable for larger numbers.
    • In count, counts.get(px + "," + py) never returns null: every point in points was 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 has px == 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 points avoids that.
    • Dropping the comma in the key. Without a separator, (1,23) and (12,3) would both become "123".
    • Storing the query. count must 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.

    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free