Problem overview
The method uniqueCount(nums) receives an array of integers and returns how many different values it contains. A value that appears several times counts once.
For [4, 7, 4, 1, 7] the different values are 4, 7 and 1, so the answer is 3. For [5, 5, 5] it is 1, and for [-2, 0, 3, 8], where nothing repeats, it is 4.
Approach
A set is a collection that holds each value at most once. Adding a value it already has changes nothing, so building a set from an array drops the repeats automatically. The number of values left in the set is the number of distinct values.
The alternative is to track the values you have already seen in an array and search it for every element, which gets slow as the input grows. A set checks membership quickly, and building one from the array takes a single pass.
Step by step
- Build a set from the array with
new Set(nums)and store it inunique. TheSetconstructor accepts any iterable and adds each item. - Return
unique.size, the number of values in the set.
The solution in JavaScript
class Solution {
uniqueCount(nums) {
let unique = new Set(nums);
return unique.size;
}
}
Two details trip people up in JavaScript. First, a set reports its count with size, a property, while arrays use length. Writing unique.length gives undefined, not an error, so the function would quietly return the wrong thing. Second, size is a property, so it takes no parentheses: unique.size() throws a TypeError.
A Set compares values with the "same value zero" rule, which behaves like === except that NaN equals itself. The number 1 and the string "1" are different values, so new Set([1, "1"]).size is 2. For the integers in this lesson, equal numbers are the same value, and the rule needs no extra thought.
Tracing the example
For [4, 7, 4, 1, 7], the set is filled as the constructor reads the array. The 4 is added, then the 7, then the second 4 finds itself already present and does nothing, then the 1 is added, and the second 7 does nothing. The set holds 4, 7 and 1, and its size is 3. Printing the set for [4, 7, 4] shows Set(2) {4, 7}: a set keeps the order of first insertion.
Complexity
Time: O(n). The constructor adds each of the n numbers once, and each addition takes constant time on average.
Space: O(k), where k is the number of distinct values, at most n. The set stores one entry per distinct value.
Edge cases and common mistakes
- Using
lengthon the set. It isundefined. Usesize. - Returning the set. The task asks for a number, so return
unique.size, notunique. - Sorting and comparing neighbours. That also works, but
sort()without a comparator orders numbers as text:[10, 9, 1].sort()gives[1, 10, 9]. The set avoids the problem entirely. - Negative numbers and zero. They are ordinary values:
[-2, 0, 3, 8]has 4 distinct values. - One repeated value.
[5, 5, 5]gives 1.
Testing
[4, 7, 4, 1, 7]gives3.[5, 5, 5]gives1.[-2, 0, 3, 8]gives4.
