</>

2013. Detect Squares

Medium NeetCode 150
Math & Geometry Time O(1) Space O(N)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Math & Geometry
Time
O(1)
Space
O(N)

Standard Solution (C++)

SummaryDesign a data structure that supports adding 2-D integer points and querying how many axis-aligned squares can be formed using a given point as one corner, with each distinct four-point combination counted once (including duplicates from repeated adds).

Approach
  • Store each point's frequency in a 2-D count grid (heap-allocated 1001×1001) and maintain a map from x-coordinate to the set of distinct y-values seen at that x.
  • For a query point (qx, qy), iterate over every distinct y-value y2 recorded at the same x-column. The vertical edge (qx,qy)-(qx,y2) defines the side length d = |y2-qy|.
  • A valid axis-aligned square needs two more corners at (qx±d, qy) and (qx±d, y2); multiply their counts together and accumulate. Multiplying frequencies correctly counts every combination of duplicate points.
  • add is O(1) amortised; count is O(N) where N is the number of distinct y-values stored in the query's x-column.
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <cstdlib>
using namespace std;

class DetectSquares {
    // freq[x][y] = how many times (x,y) has been added
    vector<vector<int>> freq;
    // ys_at[x] = distinct y-values seen at column x
    unordered_map<int, unordered_set<int>> ys_at;

public:
    DetectSquares() : freq(1001, vector<int>(1001, 0)) {}

    void add(vector<int> point) {
        int x = point[0], y = point[1];
        freq[x][y]++;
        ys_at[x].insert(y);   // set ignores duplicates automatically
    }

    int count(vector<int> point) {
        int qx = point[0], qy = point[1];
        int result = 0;

        // No points share the query's x-column -> no squares possible
        if (!ys_at.count(qx)) return 0;

        // Fix the second point on the same vertical line as the query
        for (int y2 : ys_at[qx]) {
            if (y2 == qy) continue;          // must form a non-degenerate edge
            int d = abs(y2 - qy);            // side length

            // Try both horizontal directions for the other two corners
            for (int dx : {-d, d}) {
                int nx = qx + dx;
                if (nx < 0 || nx > 1000) continue;
                // Multiply counts: each combination is one valid square
                result += freq[qx][y2] * freq[nx][qy] * freq[nx][y2];
            }
        }
        return result;
    }
};
Time O(1) for add; O(N) for count where N is the number of distinct y-values in the query's x-column Space O(C) for the frequency grid (C = 1001×1001 constant) plus O(N) for the column-to-y-set map

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class DetectSquares {
public:
    vector<vector<int>> cnts;
    unordered_map<int, vector<int>> x_to_y;
    DetectSquares():cnts(1001, vector<int>(1001, 0)) {}
    
    void add(vector<int> point) {
        if(cnts[point[0]][point[1]]++ ==0){
            x_to_y[point[0]].push_back(point[1]);
        }
    }
    
    int count(vector<int> point) {
        int x=point[0];
        int y=point[1];
        int res=0;

        auto it=x_to_y.find(x);
        if(it==x_to_y.end()){
            return 0;
        }
        
        for(const int& y2: it->second){
            if(y2==y){
                continue;
            }
            int d=std::abs(y2-y);
            if(x-d>=0){
                res+=cnts[x][y2]*cnts[x-d][y]*cnts[x-d][y2];
            }
            if(x+d<=1000){
                res+=cnts[x][y2]*cnts[x+d][y]*cnts[x+d][y2];
            }
        }

        return res;
    }
};

// Time Complexity: O(1) for add, O(N) for count
// Space Complexity: O(N) for cnts, O(N) for x_to_y
Time O(1) Space O(N)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground C++

Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.

C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern