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
- Create the set.
HashSet<Integer> unique = new HashSet<>();starts empty. Like aHashMap, it holds objects, so the element type isIntegerand Java converts fromintby itself. - Loop over the numbers with
for (int num : nums). AHashSetcan't be built straight from anint[], so the numbers go in one at a time. - Add each number with
unique.add(num). A repeat isn't stored twice. - 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:
addreturns a boolean. It istruewhen the value was new andfalsewhen it was already there. The lesson ignores the result, because the final size is all it needs.- Autoboxing.
unique.add(num)boxes theintinto anInteger. Sets ofIntegercompare by value throughequalsandhashCode, 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()gives3for a list of boxed values. It doesn't apply to anint[]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: usesize(). - 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 theintrange. - Counting duplicates by hand. A
HashSetalready does the job; a manual comparison of every pair is slower and longer.
Testing
[4, 7, 4, 1, 7]gives3.[5, 5, 5]gives1.[-2, 0, 3, 8]gives4.[1000000000, -1000000000, 1000000000]gives2.
