Problem overview
The method uniqueCount receives an array of integers, nums, and returns how many different values it has. A value that appears several times counts once. The array has at least one number.
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.
Approach
A Set is a collection that holds each value only once. Adding a value that is already inside changes nothing, and asking whether a value is inside is fast. Building a set from an array therefore throws away the repeats, and the size of the set is the number of different values.
The constructor does the work: new Set(nums) reads every item of the array and adds it. For [4, 7, 4, 1, 7] the set ends up with three values, 4, 7 and 1, in the order they first appeared.
A set is the right tool whenever the question is "have I seen this value?" or "how many different values are there?". The order of the values doesn't matter for those questions, and the set answers them without any loop or comparison of your own. The alternative is a nested loop that compares every number with every other one, which is slower and much easier to get wrong.
Because the answer is just the size of the set, the method needs no loop at all. Two lines are enough, and each one does a single clear job: collect the different values, then count them.
Step by step
- Build the set.
new Set(nums)creates a set holding the values ofnums. It is stored inunique, declared withlet. - Return its size. A set reports how many values it holds with
size, a property, not a method.
The solution in TypeScript
class Solution {
uniqueCount(nums: number[]): number {
let unique: Set<number> = new Set(nums);
return unique.size;
}
}
Details worth knowing:
- The type of the variable.
Setis a generic type, so a set of numbers is writtenSet<number>. The annotation is erased when TypeScript compiles to JavaScript, and you could leave it out and let TypeScript infer it. size, notlength. Arrays havelength. A set hassize, andunique.lengthisundefined.- Equal numbers collapse. The set compares numbers by value, so
1and1.0are the same number and count once. - The array is not changed.
new Set(nums)copies the values into a new collection.
Edge cases and common mistakes
- Using
unique.length. It givesundefinedinstead of the count. - Returning
nums.length. That counts repeats too. For[5, 5, 5]it gives 3 instead of 1. - Calling
size(). It is a property, so the parentheses are an error: a number is not a function. - One value. A single number, or the same number many times, gives 1.
- Negative numbers and zero are ordinary values and are counted like the rest.
Testing
[4, 7, 4, 1, 7]gives3.[5, 5, 5]gives1.[-2, 0, 3, 8]gives4.[1, 2, 2]gives2, while the array's ownlengthis 3.
