Start learning free

LESSON 600 OF 673 · MATH

Detect Squares in Python: O(n) Count with a Dictionary of Points

Practice O(n) Read the full explanation

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

Each point is a list [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

    PYTHON · MATH

    Detect Squares in Python, explained

    Problem overview

    The class DetectSquares starts with no points. Each point is a list [x, y] of two integers. add(point) stores a point, and adding the same point twice stores it twice. count(point) returns how many squares have point as one corner and stored points as the other three. The squares have two horizontal and two vertical sides, and the side is at least 1 long. Each copy of a stored point is a separate corner, so copies multiply the number of squares. count does not store its point.

    Take these calls on a new object: add([2, 1]), add([6, 5]), add([2, 5]), count([6, 1]), count([4, 3]), add([2, 5]), count([6, 1]). The counts are 1, 0 and 2. The corners (2, 1), (6, 5), (2, 5) and (6, 1) form one square. The point (4, 3) is the middle of it, not a corner. After the second copy of (2, 5) is added, each copy makes its own square. The tests show the results of the count calls as values separated by spaces: 1 0 2.

    The statement asks for count in O(n) time, where n is the number of different stored points.

    Approach: try each stored point as the opposite corner

    A square with sides parallel to the axes is fixed by two opposite corners. If the query point is (x, y) and the opposite corner is (px, py), the other two corners must be (px, y) and (x, py). So count can try every stored point as the opposite corner. For it to give a real square, the corner must differ in x from the query point (otherwise the side would be 0) and be as far away horizontally as vertically: abs(px - x) == abs(py - y).

    Each of the three stored corners can be any of its copies, so the number of squares for one opposite corner is the product of three counts: copies of (px, py), of (px, y) and of (x, py). A missing point has a count of 0, which makes the whole product 0.

    To look up a count in constant time, the class keeps a dictionary counts from each point to how many times it was added. To loop over the different points without scanning every possible coordinate, it also keeps a list points with each different point once. Looping over that list is what makes count take O(n), where a point added many times still costs one step.

    After the example calls and the extra copy of (2, 5), the two fields hold:

    counts: {(2, 1): 1, (6, 5): 1, (2, 5): 2}
    points: [(2, 1), (6, 5), (2, 5)]

    Step by step

    1. In __init__, set self.counts to an empty dictionary. It will map each point to the number of times it was added.
    2. Set self.points to an empty list. It will hold each different point once.
    3. In add, turn the point into a tuple, key = (point[0], point[1]). A list can't be a dictionary key, but a tuple can, and two tuples with the same numbers find the same entry.
    4. Add 1 to its count with self.counts.get(key, 0) + 1. get returns 0 when the key is not in the dictionary yet.
    5. If the new count is 1, append the key to self.points. A point added again is already in the list, so only its count grows.
    6. In count, unpack the point into x and y. Nothing is stored.
    7. Start total at 0. Several stored points can each be the opposite corner of some squares.
    8. Loop over self.points, unpacking each into px and py.
    9. Check that it can be the opposite corner: px != x and abs(px - x) == abs(py - y). Equal distances in both directions make a square, and px != x rules out a side of 0.
    10. Multiply the counts of the other two corners, (px, y) and (x, py), using get with 0 for a missing one. Store the product in corners.
    11. Add the count of (px, py) times corners to total. This is the key line. Any copy of each corner can be picked, so the counts multiply.
    12. Return total.

    The solution in Python

    class DetectSquares:
        def __init__(self):
            self.counts = {}
            self.points = []
        def add(self, point: List[int]) -> None:
            key = (point[0], point[1])
            self.counts[key] = self.counts.get(key, 0) + 1
            if self.counts[key] == 1:
                self.points.append(key)
        def count(self, point: List[int]) -> int:
            x, y = point
            total = 0
            for px, py in self.points:
                if px != x and abs(px - x) == abs(py - y):
                    corners = self.counts.get((px, y), 0) * self.counts.get((x, py), 0)
                    total += self.counts[(px, py)] * corners
            return total
    

    Python details:

    • Dictionary keys must be hashable. Using a list as a key raises TypeError: unhashable type: 'list', which is why add builds a tuple first.
    • self.counts.get(key, 0) returns a default for a missing key. Writing self.counts[(px, y)] instead would raise a KeyError when the point was never added. The last line, self.counts[(px, py)], is safe because (px, py) comes from self.points and is always a key.
    • x, y = point and for px, py in self.points unpack a list and tuples into two names.
    • Python integers do not overflow, so the product of three counts needs no special care. The statement promises the answer fits in 32 bits anyway.

    To try the class in a file of your own, the methods are used as usual:

    d = DetectSquares()
    for p in ([2, 1], [6, 5], [2, 5]):
        d.add(p)
    print(d.count([6, 1]))
    print(d.count([4, 3]))
    d.add([2, 5])
    print(d.count([6, 1]))
    

    It prints 1, 0 and 2 on separate lines, matching the statement. In a file of your own you also need from typing import List for the annotations.

    Complexity

    add does a constant amount of work: one dictionary update and at most one append. count visits each different stored point once and does constant work per point, so it takes O(n) time for n different points. The space is O(n) for the dictionary and the list.

    Edge cases and common mistakes

    • Same point as the query. With two copies of (4, 4) stored, count([4, 4]) returns 0, because a square needs a side of at least 1. Without the px != x check the same query returns 8.
    • The query point is not stored. A point can complete squares without being added, as count([6, 1]) does in the example. Storing the query would change later answers.
    • Rectangles that are not squares. In the statement's second example, (1, 0) makes a rectangle with (1, 3), (3, 0) and (3, 3), 2 wide and 3 tall. The distance check abs(px - x) == abs(py - y) rejects it, and the result is 2.
    • A list as the key. Using the incoming point list directly raises a TypeError.

    Testing

    CallsCounts printed
    the first example above1 0 2
    add([1, 1]), add([1, 3]), add([3, 1]), add([6, 3]), add([6, 0]), add([3, 0]), add([1, 0]), count([3, 3])2
    add([4, 4]) twice, count([4, 4]), add([4, 7]), add([7, 4]), count([7, 7]), count([4, 4])0 2 0
    add([1, 3]), add([3, 0]), add([1, 0]), count([3, 3])0
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free