CodeArchon

mediumMath & GeometryGoogle

Collinear Square Detector

A geometry service maintains a growing cloud of points and, on demand, counts axis-aligned squares that include a query point as one corner.

Design a data structure that supports add(point) and count(point): return the number of ways to pick 3 other recorded points to form an axis-aligned square whose fourth corner is point.

Choose approach

add(3,10)
0
i
add(11,2)
1
add(3,2)
2
count(11,10)
3
Mapcount
3,10→1
1/4
Narrationstep 1 of 4

add(3,10) → count=1.

1class DetectSquares:
2 def __init__(self):
3 self.count = {}
4 def add(self, p):
5 k = (p[0], p[1])
6 self.count[k] = self.count.get(k, 0) + 1
7 def count_squares(self, p):
8 px, py = p
9 res = 0
10 for (x, y), c in self.count.items():
11 if abs(x - px) != abs(y - py) or x == px or y == py: continue
12 res += c * self.count.get((x, py), 0) * self.count.get((px, y), 0)
13 return res
Variables
step=0
op=add
x=3
y=10

How to think about it

  1. Keep count map for duplicate corners.
  2. Only candidate diagonals have |Δx|=|Δy|.

Edge cases to catch in interview

  • Duplicates multiply the count.
  • Degenerate (same point) excluded via Δx>0 check.

Examples

Example 11
{"operations":[["add",[3,10]],["add",[11,2]],["add",[3,2]],["count",[11,10]]],"values":["add(3,10)","add(11,2)","add(3,2)","count(11,10)"]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed