Problem overview
This lesson is a class-style design problem. A DetectSquares value stores points on a grid, each point being two integers [x, y], and supports two operations:
Add(point)stores a point. Adding the same point twice stores it twice.Count(point)returns the number of squares that havepointas one corner and three stored points as the other corners. It does not store its point.
The squares are axis-aligned: two horizontal and two vertical sides, each at least 1 long. Every stored copy of a point is a separate corner, so duplicates multiply the count. In Go the starter code uses Constructor, Add and Count, with the receiver written as a pointer to DetectSquares, and the lesson provides a helper abs for integers.
In Example 1 the calls add (2,1), (6,5) and (2,5). Then Count([6 1]) returns 1, the square with corners (2,1), (6,5), (2,5) and (6,1), while Count([4 3]) returns 0 because (4,3) is the middle of that square. After a second (2,5) is added, Count([6 1]) returns 2, one square for each copy. The output is 1 0 2.
Approach: pick the opposite corner, look up the other two
Given the query corner (x, y), the opposite corner of a square can only be a stored point (px, py) that is as far from it horizontally as vertically: abs(px - x) == abs(py - y), and not zero, because a square needs positive side length. Once the opposite corner is chosen, the other two corners are forced: (px, y) and (x, py).
So the solution tries each stored point as the opposite corner. For a valid one, the number of squares is the number of copies of the opposite corner times the copies of the two forced corners. The counts multiply because any copy of each corner can be picked independently. Summing over all choices of the opposite corner gives the answer, and it needs no search over the other points.
The data structure needs a fast "how many copies of this point?" lookup, so it keeps a map from point to count, plus a list of the different points to loop over.
Step by step
- Add two fields to the struct.
countshas typemap[[2]int]intand maps each point to the number of times it was added.pointshas type[][2]intand holds each different point once. - Make the map in
Constructor, returning aDetectSquareswhosecountsismap[[2]int]int{}. Writing to a nil map panics, so it must be created. A nilpointsslice is fine becauseappendgrows it. - In
Add, build the key[2]int{point[0], point[1]}. - Count it:
this.counts[key]++. A key not yet in the map reads as 0, so the first copy makes it 1. - Remember new points. If
this.counts[key]is now 1, appendkeytothis.points. A point added again is already listed. - In
Count, read the query intox, yand starttotalat 0. The method only reads the fields. - Loop over
this.points, unpacking each intopx, py. - Test for an opposite corner:
px != xtogether withabs(px-x) == abs(py-y). Whenpxequalsx, both distances would be 0 and the "square" would have no size. - Multiply the forced corners' counts into
corners:this.counts[[2]int{px, y}] * this.counts[[2]int{x, py}]. A missing corner reads as 0, which makes the product 0, so no extra check is needed. - Add to the total
this.counts[p] * corners, then returntotalafter the loop.
The solution in Go
type DetectSquares struct {
counts map[[2]int]int
points [][2]int
}
func Constructor() DetectSquares {
return DetectSquares{counts: map[[2]int]int{}}
}
func (this *DetectSquares) Add(point []int) {
key := [2]int{point[0], point[1]}
this.counts[key]++
if this.counts[key] == 1 {
this.points = append(this.points, key)
}
}
func (this *DetectSquares) Count(point []int) int {
x, y := point[0], point[1]
total := 0
for _, p := range this.points {
px, py := p[0], p[1]
if px != x && abs(px-x) == abs(py-y) {
corners := this.counts[[2]int{px, y}] * this.counts[[2]int{x, py}]
total += this.counts[p] * corners
}
}
return total
}
The Go details worth a closer look:
- Arrays can be map keys, slices cannot. A map key type must be comparable with
==. Slices are not, somap[[]int]intfails withinvalid map key type []int. An array such as[2]intcompares element by element, so two arrays with the same numbers are the same key. That is whyAddcopies the slice's two numbers into a[2]intfirst. The copy is independent: changing the caller's slice afterwards does not change the stored key. - Reading a missing key gives the zero value, 0 for an
intcount. That is what letsthis.counts[key]++and the corner lookups work without existence checks, and a lookup never inserts anything. - Pointer receivers.
Addchanges the struct's slice, so its receiver is*DetectSquares.appendmay return a new slice header, which is why the result is assigned back tothis.points. The namethisis an ordinary identifier, not a keyword. - Looping order. Ranging over a map visits keys in random order, but the total does not depend on order. The slice
pointsis just a plain list to loop over.
With the three example call lists, the lesson's code prints 1 0 2, 2 and 0 2 0. In Example 3 the first Count([4 4]) returns 0 because the only stored point is (4,4) itself, and the last returns 0 because (7,7), the only possible opposite corner, was never stored.
Complexity
Add is O(1): one map update and at most one append. Count loops over the different points once and does a constant amount of work for each, so it takes O(n), where n is the number of different points stored. The structure keeps one map entry and one list entry per different point, so the space is O(n).
Edge cases and common mistakes
- Zero-size squares. A query equal to a stored point must not pair with that same point. Requiring
px != xexcludes it, and then equal distances forcepy != ytoo. - Duplicates. If each point were stored once, the count in Example 1 after the second
(2,5)would stay 1. The map of counts keeps every copy. - Rectangles. Checking only that the two other corners exist finds rectangles. The equal-distance test is what limits the answer to squares. In Example 2,
(1,0)makes a rectangle with the query(3,3)and does not count. - Storing the query.
Countmust not add its point.
