2013. Detect Squares
Problem
Design DetectSquares: add(point) records a point (duplicates allowed), and count(point) returns how many ways you can pick three recorded points that form, together with the query point, an axis-aligned square of positive area.
Example: add [3,10], [11,2], [3,2] → count([11,10]) = 1; count([14,8]) = 0
Constraints: coordinates ≤ 1000; up to 3000 calls.
Count points. For a query (x, y), each stored point (px, py) with |px − x| = |py − y| ≠ 0 is a diagonal corner; the square count is cnt[diag] · cnt[(x, py)] · cnt[(px, y)].
(x,py) ---- (px,py) query (x,y), diagonal (px,py)
| | need the other two corners
(x,y) ---- (px,y)
Complexity: add O(1), count O(#distinct points).
class DetectSquares:
def __init__(self):
self.cnt = Counter()
def add(self, point: List[int]) -> None:
self.cnt[tuple(point)] += 1
def count(self, point: List[int]) -> int:
x, y = point
total = 0
for (px, py), c in list(self.cnt.items()):
if abs(px - x) != abs(py - y) or px == x:
continue
total += c * self.cnt[(x, py)] * self.cnt[(px, y)]
return total
ds = DetectSquares()
for p in ([3, 10], [11, 2], [3, 2]):
ds.add(p)
assert ds.count([11, 10]) == 1
assert ds.count([14, 8]) == 0
ds.add([11, 2])
assert ds.count([11, 10]) == 2
class DetectSquares {
private final Map<Long, Integer> cnt = new HashMap<>();
private final List<int[]> pts = new ArrayList<>();
private long key(int x, int y) { return (long) x * 2001 + y; }
public void add(int[] point) {
if (cnt.merge(key(point[0], point[1]), 1, Integer::sum) == 1) pts.add(point);
}
public int count(int[] point) {
int x = point[0], y = point[1], total = 0;
for (int[] p : pts) {
if (Math.abs(p[0] - x) != Math.abs(p[1] - y) || p[0] == x) continue;
total += cnt.get(key(p[0], p[1])) * cnt.getOrDefault(key(x, p[1]), 0) * cnt.getOrDefault(key(p[0], y), 0);
}
return total;
}
}
type DetectSquares struct {
cnt map[[2]int]int // point -> how many times it was added
}
func Constructor() DetectSquares {
return DetectSquares{cnt: map[[2]int]int{}}
}
func (this *DetectSquares) Add(point []int) {
this.cnt[[2]int{point[0], point[1]}]++
}
func (this *DetectSquares) Count(point []int) int {
x, y := point[0], point[1]
total := 0
for p, c := range this.cnt { // p is the corner diagonal to the query point
px, py := p[0], p[1]
if abs(px-x) != abs(py-y) || px == x {
continue
}
total += c * this.cnt[[2]int{x, py}] * this.cnt[[2]int{px, y}]
}
return total
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}