Start learning free

LESSON 623 OF 635 · OBJECT-ORIENTED PROGRAMMING - CHALLENGES

Unique Points in Java

Practice O(n)

Build a Point class 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 class Point, created by new Point(x, y). Two points are equal when their x and their y both match.
  • a method countUnique(points) in the class Solution. It returns the number of different points.

In Java, override equals and hashCode, as in Comparing Objects. Then add the points themselves to a HashSet. The set uses your two methods to drop the repeats.

The program also checks your class 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 8
    Ctrl + Enter to check

    Unique Points in Java

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