1207. Unique Number of Occurrences
Problem
Return true if every distinct value in arr occurs a different number of times than every other value.
Example: [1,2,2,1,1,3] → true (counts 3, 2, 1); [1,2] → false
Count each value, then check that no two values share a count: the number of distinct counts must equal the number of distinct values.
Complexity: O(n).
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
counts = list(Counter(arr).values())
return len(counts) == len(set(counts))
assert Solution().uniqueOccurrences([1, 2, 2, 1, 1, 3]) is True
assert Solution().uniqueOccurrences([1, 2]) is False
assert Solution().uniqueOccurrences([-3, 0, 1, -3, 1, 1, 1, -3, 10, 0]) is True
class Solution {
public boolean uniqueOccurrences(int[] arr) {
Map<Integer, Integer> cnt = new HashMap<>();
for (int x : arr) cnt.merge(x, 1, Integer::sum);
return new HashSet<>(cnt.values()).size() == cnt.size();
}
}
func uniqueOccurrences(arr []int) bool {
cnt := map[int]int{}
for _, x := range arr {
cnt[x]++
}
seen := map[int]bool{}
for _, c := range cnt {
if seen[c] {
return false
}
seen[c] = true
}
return true
}