Problem overview
The method uniqueCount receives a list of integers, 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, since nothing repeats.
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 in it changes nothing, and asking whether a value is in it is fast. Building a set from a list therefore removes the repeats automatically, and the size of the set is the number of different values.
The lesson has two steps. Build the set, then return its size.
Without a set, you would loop over the list, keep a second list of the values met so far, and add a value only if it isn't in that list yet. A set does that bookkeeping for you, and its membership test stays fast as the data grows.
Step by step
- Build the set.
unique = set(nums)takes every number of the list and keeps one of each. For[4, 7, 4], the set holds just 4 and 7. - Return its size.
len(unique)works on a set the same way it works on a list, and it counts the values the set holds.
What building the set does
You can picture set(nums) as adding the numbers one by one. For [4, 7, 4, 1, 7], the set and its size after each number are:
| number added | set afterwards | size |
|---|---|---|
| 4 | {4} | 1 |
| 7 | {4, 7} | 2 |
| 4 | {4, 7} | 2 |
| 1 | {1, 4, 7} | 3 |
| 7 | {1, 4, 7} | 3 |
The repeated 4 and 7 leave the set unchanged, so the final size is 3, the number of different values. Python builds the set in one call, so there is no loop to write, but the effect is the same.
The solution in Python
class Solution:
def uniqueCount(self, nums: List[int]) -> int:
unique = set(nums)
return len(unique)
What to know about sets:
- Sets have no order and no positions. A set doesn't remember where a value was in the list, and you can't write
unique[0]. Printing the set for[4, 7, 4]shows{4, 7}. The order isn't something to rely on. - Values must be hashable. Numbers and strings can go in a set. Lists can't, so
set([[1], [2]])raises aTypeError. {}is not an empty set. Empty braces make an empty dictionary. An empty set is writtenset().- Equal numbers are one value. The numbers are compared by value, so every 5 in
[5, 5, 5]is the same member, and the set has size 1.
Edge cases and common mistakes
- Returning
len(nums). That is the length of the list, repeats included. For[4, 7, 4, 1, 7]it is 5, while the answer is 3. - Returning the set. The function must return an integer.
return uniquewould hand back the set{1, 4, 7}, not a number. - Negative numbers and zero. They are values like any other.
[-2, 0, 3, 8]has four different values. - A single number. One number gives a set of size 1.
Testing
[4, 7, 4, 1, 7]gives3.[5, 5, 5]gives1.[-2, 0, 3, 8]gives4.
