Start learning free

LESSON 566 OF 639 · MATH

Detect Squares in TypeScript

Practice O(n)

You get a series of calls to a class, DetectSquares. It stores points on a grid.

Each point is an array [x, y] of two integers.

Implement the class:

  • DetectSquares() starts with no points.
  • add(point) stores point. A point added twice is stored twice.
  • count(point) returns the number of squares with point as one corner and stored points as the other three.

A square has two horizontal and two vertical sides. Its sides are at least 1 long.

Each copy of a stored point is a separate corner. So copies make more squares.

count doesn't store its point.

The calls run in order on one new DetectSquares. The output lists what the count calls return, in order. The starter code spells these names the way your language does.

 

Example 1:

Input:
1. add([2, 1])
2. add([6, 5])
3. add([2, 5])
4. count([6, 1])
5. count([4, 3])
6. add([2, 5])
7. count([6, 1])
Output: 1 0 2
Explanation: Call 4 finds one square.
Its corners are (2, 1), (6, 5), (2, 5) and (6, 1).
(4, 3) is the middle of that square, not a corner.
So call 5 returns 0.
Call 6 adds a second copy of (2, 5).
Each copy makes its own square, so call 7 returns 2.

Example 2:

Input:
1. add([1, 1])
2. add([1, 3])
3. add([3, 1])
4. add([6, 3])
5. add([6, 0])
6. add([3, 0])
7. add([1, 0])
8. count([3, 3])
Output: 2
Explanation: (3, 3) completes two squares of different sizes.
One has side 2, with (1, 1), (1, 3) and (3, 1).
The other has side 3, with (6, 3), (6, 0) and (3, 0).
(1, 0) makes a rectangle with (1, 3), (3, 0) and (3, 3).
It is 2 wide and 3 tall, so it doesn't count.

Example 3:

Input:
1. add([4, 4])
2. add([4, 4])
3. count([4, 4])
4. add([4, 7])
5. add([7, 4])
6. count([7, 7])
7. count([4, 4])
Output: 0 2 0
Explanation: Call 3 returns 0.
A square needs sides at least 1 long.
Call 6 returns 2.
(7, 7) completes a square with (4, 7), (7, 4) and either copy of (4, 4).
Call 7 returns 0, because (7, 7) was never stored.

 

Constraints:

  • Each x and y is a whole number from 0 to 1,000.
  • At most 5,000 calls in total.
  • Every answer of count fits in a 32-bit signed integer.

Note:

count should run in O(n) time, where n is the number of different points stored.

STEP 1 OF 12
    Ctrl + Enter to check

    Detect Squares in TypeScript

    Keep going with TypeScript500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free