Start learning free

LESSON 627 OF 639 · OBJECT-ORIENTED PROGRAMMING - CHALLENGES

Unique Points in Go

Practice O(n)

Build a Point struct whose points compare by their values. Then use it to count the different points in a list.

You get the list of points. Some points appear more than once. Return how many different points it holds.

Write:

  • a struct Point, created by NewPoint(x, y). Two points are equal when their x and their y both match.
  • a function countUnique(points). It returns the number of different points.

In Go, a struct with comparable fields is comparable, as in Comparing Objects. Its == compares the fields. It can also be a map key. So a map[Point]bool keeps each point once.

The program also checks your struct directly. It compares a point with a copy of itself, and with the points next to it.

 

Example 1:

Input: points = [(1, 2), (3, 4), (1, 2)]
Output: 2
Explanation: (1, 2) appears twice.
It is still one point.
(3, 4) is the other one.

Example 2:

Input: points = [(2, 1), (1, 2)]
Output: 2
Explanation: The same two numbers in another order make another point.

Example 3:

Input: points = [(0, 0), (0, 0), (0, 0), (0, 0)]
Output: 1
Explanation: All four are the same point.

 

Constraints:

  • 1 to 1,000 points.
  • Each coordinate is a whole number from -1,000 to 1,000.
Note:

A set adds a point in O(1) time on average. So counting n points takes O(n).

STEP 1 OF 6
    Ctrl + Enter to check

    Unique Points in Go

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