|
| 1 | +# Detect Squares |
| 2 | + |
| 3 | +**Difficulty:** Medium |
| 4 | +**Topics:** Array, Hash Table, Design, Counting, Data Stream |
| 5 | +**Tags:** neetcode-150 |
| 6 | + |
| 7 | +**LeetCode:** [Problem 2013](https://leetcode.com/problems/detect-squares/description/) |
| 8 | + |
| 9 | +## Problem Description |
| 10 | + |
| 11 | +You are given a stream of points on the X-Y plane. Design an algorithm that: |
| 12 | + |
| 13 | +- **Adds** new points from the stream into a data structure. **Duplicate** points are allowed and should be treated as different points. |
| 14 | +- Given a query point, **counts** the number of ways to choose three points from the data structure such that the three points and the query point form an **axis-aligned square** with **positive area**. |
| 15 | + |
| 16 | +An **axis-aligned square** is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and y-axis. |
| 17 | + |
| 18 | +Implement the `DetectSquares` class: |
| 19 | + |
| 20 | +- `DetectSquares()` Initializes the object with an empty data structure. |
| 21 | +- `void add(int[] point)` Adds a new point `point = [x, y]` to the data structure. |
| 22 | +- `int count(int[] point)` Counts the number of ways to form **axis-aligned squares** with point `point = [x, y]` as described above. |
| 23 | + |
| 24 | +## Examples |
| 25 | + |
| 26 | +### Example 1: |
| 27 | + |
| 28 | + |
| 29 | + |
| 30 | +``` |
| 31 | +Input |
| 32 | +["DetectSquares", "add", "add", "add", "count", "count", "add", "count"] |
| 33 | +[[], [[3, 10]], [[11, 2]], [[3, 2]], [[11, 10]], [[14, 8]], [[11, 2]], [[11, 10]]] |
| 34 | +Output |
| 35 | +[null, null, null, null, 1, 0, null, 2] |
| 36 | +
|
| 37 | +Explanation |
| 38 | +DetectSquares detectSquares = new DetectSquares(); |
| 39 | +detectSquares.add([3, 10]); |
| 40 | +detectSquares.add([11, 2]); |
| 41 | +detectSquares.add([3, 2]); |
| 42 | +detectSquares.count([11, 10]); // return 1. |
| 43 | +detectSquares.count([14, 8]); // return 0. |
| 44 | +detectSquares.add([11, 2]); // Adding duplicate points is allowed. |
| 45 | +detectSquares.count([11, 10]); // return 2. |
| 46 | +``` |
| 47 | + |
| 48 | +## Constraints |
| 49 | + |
| 50 | +- `point.length == 2` |
| 51 | +- 0 <= x, y <= 1000 |
| 52 | +- At most `3000` calls in total will be made to `add` and `count`. |
0 commit comments