#1207
Unique Number of Occurrences
Easy HashMap + HashSet
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Return true if every distinct value in the array appears a different number of times.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: are all the counts different?
Why this works: count values, then check whether the set of counts is as big as the number of values.
Example: [1, 2, 2, 1, 1, 3]
counts 1→3, 2→2, 3→1 → {3, 2, 1} all distinct → true✦Hints open one at a time
Count each value with a HashMap.
Put the counts in a HashSet; if a count repeats, return false.
↗Approach
Count frequencies, then check that the set of counts has the same size as the map.
</>Solution (Java)
import java.util.*;
class Solution {
public boolean uniqueOccurrences(int[] arr) {
Map<Integer, Integer> freq = new HashMap<>();
for (int x : arr) freq.merge(x, 1, Integer::sum);
return new HashSet<>(freq.values()).size() == freq.size();
}
}
!Common mistake
Comparing Integer counts with == — values above 127 aren't cached and compare by reference. A set avoids that.
Complexity
- Time: O(n).
- Space: O(n).
Topic: Hashing
🎬 Episodes 37–39: video coming soon