Count the axis-aligned squares a query point makes with stored points. Keep point counts in a hash map and scan for diagonal corners.
▼The problem
LeetCode 2013 (Medium). Design a class DetectSquares: add(point) stores a point on the plane (duplicates allowed, each copy counts separately) and count(point) returns the number of ways to choose three stored points that form an axis-aligned square of positive area together with the query point.
Example (LeetCode's, the one animated): add [3,10], add [11,2], add [3,2], count [11,10] → 1, count [14,8] → 0, add [11,2], count [11,10] → 2.
The solution
from collections import Counter
class DetectSquares:
def __init__(self):
self.cnt = Counter() # point -> copies
def add(self, point):
self.cnt[tuple(point)] += 1
def count(self, point):
x, y = point
ways = 0
for (px, py), n in self.cnt.items():
if abs(px - x) != abs(py - y) or px == x:
continue # off the diagonal
ways += n * self.cnt[(x, py)] * self.cnt[(px, y)]
return waysTranscript
Detect Squares. Design a class with two calls. Add stores a point, and the same point can come again: every copy counts. Count takes a query point: in how many ways do three stored points make a square with it? The sides run along the axes, and the area can't be zero.
Add three ten, eleven two, and three two. Count eleven ten: those three close one square around it, so the answer is one. Count fourteen eight: nothing lines up, so zero. Add eleven two again, and count eleven ten: now it's two, one for each copy.
The easy way tries every triple of stored points on each count, and checks it for a square. With a thousand points, that's over a hundred and sixty-six million triples for one question: order n cubed.
Here's the trick. Keep a hash map from each point to its number of copies. Picture every point as a float on a pond, with its copies stacked up. A square is fixed by just two corners: the query, and the corner diagonally opposite. So scan the map for a diagonal partner, whose distance across equals its distance down, and isn't zero. Then the other two corners are forced. Look up their counts and multiply all three, since every copy makes a different square.
In code, add just bumps a count. Count loops over the stored points, skips any that aren't on a diagonal, and adds the product of three counts to the answer.
Let's run the last count, eleven ten. Three ten shares its row, so it's skipped. Eleven two shares its column: skipped too. Three two is eight across and eight down: a diagonal partner. Its other corners, eleven two and three ten, hold two copies and one. One times two times one: two squares.
Add is order one. Count is order n: one pass over the distinct points, not every triple. And the map uses order n space.
Store the counts, find the diagonal, multiply. That's Detect Squares.