Start learning free

LESSON 630 OF 642 · OBJECT-ORIENTED PROGRAMMING - CHALLENGES

Unique Points in Rust

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 with a function new(x, y) that creates one. Two points are equal when their x and their y both match.
  • a method count_unique(points) in impl Solution. It returns the number of different points.

As in Comparing Objects, Point derives PartialEq, Eq and Hash. Then insert the points into a HashSet. The set uses those traits to drop the repeats.

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

    Unique Points in Rust

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