Detect Squares: the idea to remember.
Add points with multiplicity and count axis aligned squares formed with a query point and three stored points.
The core insight
For every stored point on the query row, use its horizontal distance as a side length and multiply the two remaining corner frequencies.
Why it works
Each nonzero horizontal partner determines exactly two possible axis aligned squares, one above and one below; frequency products count every occurrence choice.
The mistake to avoid
Repeated stored points multiply the number of squares. A zero side length is not a square.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
class DetectSquares {
private final Map<Integer,Map<Integer,Integer>> rows = new HashMap<>();
void add(int[] point) {
rows.computeIfAbsent(point[1], ignored -> new HashMap<>()).merge(point[0],1,Integer::sum);
}
int count(int[] point) {
int x = point[0], y = point[1], result = 0;
Map<Integer,Integer> row = rows.getOrDefault(y, Collections.emptyMap());
for (Map.Entry<Integer,Integer> other : row.entrySet()) {
int otherX = other.getKey(), side = otherX - x;
if (side == 0) continue;
// Each same-row partner determines a square above and below.
for (int otherY : new int[]{y + side, y - side}) {
Map<Integer,Integer> parallel = rows.getOrDefault(otherY, Collections.emptyMap());
result += other.getValue() * parallel.getOrDefault(x,0) * parallel.getOrDefault(otherX,0);
}
}
return result;
}
}
Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.