Start learning free

LESSON 230 OF 285 · SETS

Unique Count in Java: Counting Distinct Values with a HashSet

Practice Read the full explanation

Given an array of integers nums, return how many different values it has.

A value that appears several times counts only once.

 

Example 1:

Input: nums = [4, 7, 4, 1, 7]
Output: 3
Explanation: The different values are 4, 7 and 1. The second 4 and the second 7 are repeats, so they don't count again.

Example 2:

Input: nums = [5, 5, 5]
Output: 1
Explanation: Every number is 5, so there is only one different value.

Example 3:

Input: nums = [-2, 0, 3, 8]
Output: 4
Explanation: No value repeats, so every number counts.

 

Constraints:

  • nums has at least one number.
  • Every number is between -109 and 109.
STEP 1 OF 4
    Ctrl + Enter to check

    JAVA · SETS

    Unique Count in Java, explained

    Problem overview

    The method uniqueCount receives an array of integers, nums, and returns how many different values it holds. A value that appears several times counts once.

    In [4, 7, 4, 1, 7] the different values are 4, 7 and 1, so the answer is 3: the second 4 and the second 7 are repeats. [5, 5, 5] has one different value, so the answer is 1. [-2, 0, 3, 8] has no repeats, so every number counts and the answer is 4. Values go up to a billion in size, so they fit in an int.

    Approach: let a set forget the repeats

    A set is a collection that holds each value only once. Adding a value that is already inside changes nothing. Put every number into a set, and the set's size is the number of different values. You never have to compare numbers with each other yourself: the set does the duplicate check, and it is fast.

    The alternative is to compare every element with every other, which takes time proportional to the square of the array's length, or to sort first and count the changes between neighbours. A set gets the answer in one pass.

    Step by step

    1. Create the set. HashSet<Integer> unique = new HashSet<>(); starts empty. Like a HashMap, it holds objects, so the element type is Integer and Java converts from int by itself.
    2. Loop over the numbers with for (int num : nums). A HashSet can't be built straight from an int[], so the numbers go in one at a time.
    3. Add each number with unique.add(num). A repeat isn't stored twice.
    4. Return the size with unique.size(), the number of values the set holds, after the loop.

    The solution in Java

    class Solution {
        public int uniqueCount(int[] nums) {
            HashSet<Integer> unique = new HashSet<>();
            for (int num : nums) {
                unique.add(num);
            }
            return unique.size();
        }
    }
    

    This is how the set grows on [4, 7, 4, 1, 7]:

    4 -> [4] size 1
    7 -> [4, 7] size 2
    4 -> [4, 7] size 2
    1 -> [1, 4, 7] size 3
    7 -> [1, 4, 7] size 3
    

    The second 4 and the second 7 leave the set unchanged. The printed order of a HashSet isn't something to rely on, and it isn't the order of insertion.

    Java details worth knowing:

    • add returns a boolean. It is true when the value was new and false when it was already there. The lesson ignores the result, because the final size is all it needs.
    • Autoboxing. unique.add(num) boxes the int into an Integer. Sets of Integer compare by value through equals and hashCode, so two boxed 1000s are the same element, even though they are two objects.
    • A shorter form. new HashSet<>(Arrays.asList(4, 7, 4, 1, 7)).size() gives 3 for a list of boxed values. It doesn't apply to an int[] directly, which is why the lesson uses the loop.

    Complexity

    Time: O(n) for n numbers, since add costs a constant amount on average. Space: O(k), where k is the number of different values, because the set holds each one once.

    Edge cases and common mistakes

    • Returning nums.length. That counts every element, repeats included. For [5, 5, 5] it gives 3 instead of 1.
    • Returning the set. The method returns an int: use size().
    • Negative numbers and zero. They are ordinary values: [-2, 0, 3, 8] gives 4.
    • Large values. [1000000000, -1000000000, 1000000000] gives 2. The limit of a billion keeps every value inside the int range.
    • Counting duplicates by hand. A HashSet already does the job; a manual comparison of every pair is slower and longer.

    Testing

    • [4, 7, 4, 1, 7] gives 3.
    • [5, 5, 5] gives 1.
    • [-2, 0, 3, 8] gives 4.
    • [1000000000, -1000000000, 1000000000] gives 2.
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free