Start learning free

LESSON 314 OF 314 · MATH

Detect Squares in Go: Counting Points in a Map with Array Keys

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 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 14
    Ctrl + Enter to check

    GO · MATH

    Detect Squares in Go, explained

    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 have point as 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

    1. Add two fields to the struct. counts has type map[[2]int]int and maps each point to the number of times it was added. points has type [][2]int and holds each different point once.
    2. Make the map in Constructor, returning a DetectSquares whose counts is map[[2]int]int{}. Writing to a nil map panics, so it must be created. A nil points slice is fine because append grows it.
    3. In Add, build the key [2]int{point[0], point[1]}.
    4. Count it: this.counts[key]++. A key not yet in the map reads as 0, so the first copy makes it 1.
    5. Remember new points. If this.counts[key] is now 1, append key to this.points. A point added again is already listed.
    6. In Count, read the query into x, y and start total at 0. The method only reads the fields.
    7. Loop over this.points, unpacking each into px, py.
    8. Test for an opposite corner: px != x together with abs(px-x) == abs(py-y). When px equals x, both distances would be 0 and the "square" would have no size.
    9. 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.
    10. Add to the total this.counts[p] * corners, then return total after 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, so map[[]int]int fails with invalid map key type []int. An array such as [2]int compares element by element, so two arrays with the same numbers are the same key. That is why Add copies the slice's two numbers into a [2]int first. 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 int count. That is what lets this.counts[key]++ and the corner lookups work without existence checks, and a lookup never inserts anything.
    • Pointer receivers. Add changes the struct's slice, so its receiver is *DetectSquares. append may return a new slice header, which is why the result is assigned back to this.points. The name this is 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 points is 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 != x excludes it, and then equal distances force py != y too.
    • 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. Count must not add its point.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free