Detect Squares

MediumDesignhashing

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Maintain a multiset of points on a 2-D integer grid and answer square-counting queries. - DetectSquares() starts with no points. - add(point) inserts point = [x, y]. The same coordinates may be added multiple times; each copy is a separate point. - count(point) returns the number of ways to choose **three stored points** that, together with the query point [x, y], form an **axis-aligned square with positive area**. Two ways are different if they use a different stored copy for at least one corner. The query point itself is not stored by count. Each add should be O(1), and each count should be proportional to the number of distinct stored points sharing the query's x-coordinate (or similar).

Examples

Input: ["DetectSquares","add","add","add","count","count","add","count"] [[],[[1,1]],[[4,1]],[[1,4]],[[4,4]],[[2,2]],[[1,4]],[[4,4]]]
Output: [null,null,null,null,1,0,null,2]
Query (4,4) pairs with (1,4), (4,1) and (1,1) to form a side-3 square. No square fits around (2,2). After a second copy of (1,4) is added, each copy gives a separate square, so the count is 2.
Input: ["DetectSquares","add","add","count","add","add","add","count","count"] [[],[[5,5]],[[5,5]],[[5,5]],[[7,5]],[[5,7]],[[7,7]],[[5,5]],[[7,7]]]
Output: [null,null,null,0,null,null,null,1,2]
Points on top of the query cannot form a square with positive area. From (5,5) there is one side-2 square; from (7,7) the diagonal corner (5,5) has two copies, giving 2.

Constraints

  • `point.length == 2`
  • 0 <= x, y <= 1000
  • At most 3000 calls are made to `add` and `count` in total.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More hashing problems