The Detect Squares interview question asks you to design a data structure that processes a stream of 2D points. You need to implement add(point) to store coordinates and count(point) to find the number of ways to form an axis-aligned square using the given point as one of the corners and three other points from the stored collection.
Google and Meta use this to test your ability to handle spatial data using hash tables. It evaluations your skill in identifying geometry properties (like how to uniquely define a square given two diagonal points) and your ability to optimize lookups in a data stream. It’s a great test of "Counting" logic using multiplication of frequencies.
This problem uses Hash Tables and Coordinate Geometry.
Map<X, Map<Y, Count>> or a single Map<Point, Count>.count(px, py) is called:
(px, y).side = abs(y - py).side > 0, check for the other two points needed to complete the square: (px + side, py) and (px + side, y) OR (px - side, py) and (px - side, y).Points added: (3, 10), (11, 2), (3, 2), (11, 10).
Query count(11, 10):
(11, 2). Side length = 8.(11-8, 10) and (11-8, 2).(3, 10) and (3, 2) exist. Both exist.Always use a Hash Map to store point frequencies when dealing with "counting combinations." Geometric properties (like diagonals or sides) often allow you to narrow down the search space to a single dimension.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Design an Ordered Stream | Easy | Solve | |
| First Unique Number | Medium | Solve | |
| Find Consecutive Integers from a Data Stream | Medium | Solve | |
| Tuple with Same Product | Medium | Solve | |
| Two Sum III - Data structure design | Easy | Solve |