Algo-Sim › Math & Geometry

Detect Squares

Medium · Math & Geometry · step through it in Java, Python and C++ on your own input

Count axis-aligned squares that a query point completes with stored points. Keep point counts in a hash map; each diagonal partner fixes the other two corners, and the counts multiply.

Problem

Design DetectSquares. add(point) stores a point [x, y]; the same point may be added more than once, and each copy counts separately. count(point) returns the number of ways to pick three stored points that, with the query point, form a square with positive area and sides parallel to the axes.

Constraints

Edge cases to test

Follow-up questions

Why iterate over points with the same x, not all points?
Grouping by x and storing counts per (x, y) makes count O(points on that column) instead of O(all points).
What about squares that aren’t axis-aligned?
For each other point as the diagonal, compute the two remaining corners and look them up: O(n) per query with a hash map.

Solution

Java

class DetectSquares {
    private final Map<List<Integer>, Integer> counts = new HashMap<>();

    private int get(int x, int y) {
        return counts.getOrDefault(List.of(x, y), 0);
    }

    public void add(int[] point) {
        counts.merge(List.of(point[0], point[1]), 1, Integer::sum);
    }

    public int count(int[] point) {
        int x = point[0], y = point[1], total = 0;
        for (Map.Entry<List<Integer>, Integer> e : counts.entrySet()) {
            int px = e.getKey().get(0), py = e.getKey().get(1);
            if (px == x || Math.abs(px - x) != Math.abs(py - y)) continue;
            total += e.getValue() * get(x, py) * get(px, y);
        }
        return total;
    }
}

Python

from collections import Counter


class DetectSquares:
    def __init__(self):
        self.counts = Counter()

    def add(self, point):
        self.counts[tuple(point)] += 1

    def count(self, point):
        x, y = point
        total = 0
        for (px, py), c in self.counts.items():
            if px == x or abs(px - x) != abs(py - y):
                continue
            # A missing key reads as 0 and is not inserted.
            total += c * self.counts[(x, py)] * self.counts[(px, y)]
        return total

C++

#include <bits/stdc++.h>
using namespace std;

class DetectSquares {
    map<pair<int, int>, int> counts;

    // Read without inserting: operator[] would add keys mid-scan.
    int get(int x, int y) {
        auto it = counts.find({x, y});
        return it == counts.end() ? 0 : it->second;
    }

  public:
    void add(vector<int> point) {
        counts[{point[0], point[1]}]++;
    }

    int count(vector<int> point) {
        int x = point[0], y = point[1], total = 0;
        for (auto &[p, c] : counts) {
            auto [px, py] = p;
            if (px == x || abs(px - x) != abs(py - y)) {
                continue;
            }
            total += c * get(x, py) * get(px, y);
        }
        return total;
    }
};

More Math & Geometry problems