Problem overview
The method UniqueCount receives an int[] named nums and returns how many different values it holds. A value that appears several times counts once.
For [4, 7, 4, 1, 7] the answer is 3: the different values are 4, 7 and 1. For [5, 5, 5] it is 1, and for [-2, 0, 3, 8] it is 4, because nothing repeats. The array has at least one number, and the numbers are between -1,000,000,000 and 1,000,000,000, so they fit in an int.
Approach: let a set remove the repeats
A set is a collection that holds each value at most once. Adding a value that is already inside changes nothing. Checking whether a value is in the set is fast. C#'s set type is HashSet<T>.
That is exactly the tool for this problem. Put all the numbers into a HashSet<int>, and the repeats collapse by themselves. The number of values left in the set is the number of different values in the array.
A HashSet can be built straight from an array: new HashSet<int>(nums) creates a set that starts with the array's values. No loop is needed. For [4, 7, 4, 1, 7] the set ends up holding 4, 7 and 1.
Without a set, you would need a second collection and a loop: for each number, check whether it was already collected, and add it if not. You would then count the collected values. The set does the checking inside Add and in the constructor, so the whole method shrinks to two lines. Sorting the array and counting the places where the value changes is another way, but it needs more code and reorders data you may want to keep.
It is also fast. Building the set visits each number once, and each insertion takes constant time on average, so the work grows in step with the length of the array, O(n). The set holds at most one entry per distinct value, so the extra space is O(k) for k distinct values.
Step by step
- Create the set:
HashSet<int> unique = new HashSet<int>(nums);. It starts with the values ofnums, each one once. - Return its size,
unique.Count. A set reports its size withCount, notLength.
The solution in C#
class Solution {
public int UniqueCount(int[] nums) {
HashSet<int> unique = new HashSet<int>(nums);
return unique.Count;
}
}
Details worth knowing:
- A set has no indexes. You can't write
unique[0], and you shouldn't count on any particular order when you go over it. - The
Addmethod of aHashSetreturns abool:trueif the value was new andfalseif it was already there. Adding 4 to a set that holds 4 givesfalse, and adding 7 givestrue. - Arrays use
Length, lists and sets useCount. Writingunique.Lengthdoesn't compile.
Edge cases and common mistakes
- Returning
nums.Length. That counts every element, repeats included. - Using
unique.Length. AHashSethasCount. - All the same value.
[5, 5, 5]gives a set with one value, so the answer is 1. - Negative numbers and zero. They are ordinary values and count like any other.
Testing
| nums | Result |
|---|---|
[4, 7, 4, 1, 7] | 3 |
[5, 5, 5] | 1 |
[-2, 0, 3, 8] | 4 |
