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
- In
__init__, setself.countsto an empty dictionary. It will map each point to the number of times it was added. - Set
self.pointsto an empty list. It will hold each different point once. - 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. - Add 1 to its count with
self.counts.get(key, 0) + 1.getreturns 0 when the key is not in the dictionary yet. - 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. - In
count, unpack the point intoxandy. Nothing is stored. - Start
totalat 0. Several stored points can each be the opposite corner of some squares. - Loop over
self.points, unpacking each intopxandpy. - Check that it can be the opposite corner:
px != xandabs(px - x) == abs(py - y). Equal distances in both directions make a square, andpx != xrules out a side of 0. - Multiply the counts of the other two corners,
(px, y)and(x, py), usinggetwith 0 for a missing one. Store the product incorners. - Add the count of
(px, py)timescornerstototal. This is the key line. Any copy of each corner can be picked, so the counts multiply. - 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 whyaddbuilds a tuple first. self.counts.get(key, 0)returns a default for a missing key. Writingself.counts[(px, y)]instead would raise aKeyErrorwhen the point was never added. The last line,self.counts[(px, py)], is safe because(px, py)comes fromself.pointsand is always a key.x, y = pointandfor px, py in self.pointsunpack 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 thepx != xcheck 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
pointlist directly raises aTypeError.
Testing
| Calls | Counts printed |
|---|---|
| the first example above | 1 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 |
