On this page
1207. Unique Number of Occurrences
Count frequencies, then check that all occurrence counts are unique.
Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise.
- Input:
- arr = [1,2,2,1,1,3]
- Output:
- true
- Explanation:
- The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
- Input:
- arr = [1,2]
- Output:
- false
- Input:
- arr = [-3,0,1,-3,1,1,1,-3,10,0]
- Output:
- true
- 1 <= arr.length <= 1000
- -1000 <= arr[i] <= 1000
Understand the problem
Two layers. First, count the frequency of each value (dict/Counter). Second, check whether those occurrence counts themselves have any duplicates.
A common duplicate check: compare len(list) with len(set(list)). If equal, nothing was duplicated (a set shrinks when duplicates exist).
Approach
- Count frequencies with Counter(arr) → key = value, value = occurrences
- Pull only the occurrence counts via .values()
- Compare len of those counts with len of their set
- Equal → no duplicate occurrences → return True; else False
Don’t check the keys (the values themselves) instead of the occurrence counts. Use .values(), not .keys() — keys are unique by definition of a dict.
Walkthrough — arr = [1, 2, 2, 1, 1, 3]
- Counter(arr) → {1: 3, 2: 2, 3: 1}
- .values() → occurrence counts [3, 2, 1]
- set([3, 2, 1]) = {1, 2, 3} same length → no duplicates → True
Contrast arr = [1, 2]: Counter → {1: 1, 2: 1} · values = [1, 1] · set shrinks to {1} → False
Try it yourself first
Approach and walkthrough are above — write it yourself, then open the fold below when stuck or ready to compare.
Solution code · folded so you can try firstพับไว้ด้านใน — คลิกเมื่อพร้อมดู
Core: count frequencies first, then ask whether occurrence counts are unique via len vs set.
from collections import Counter
def unique_occurrences(arr):
counts = Counter(arr).values() # occurrence counts, e.g. [3, 2, 1]
# if putting values into a set keeps the same length, there were no duplicates
return len(counts) == len(set(counts))
print(unique_occurrences([1, 2, 2, 1, 1, 3])) # True
print(unique_occurrences([1, 2])) # False
print(unique_occurrences([3, 5, 7, 7, 5, 5])) # TrueTrue
False
TrueWhat to notice
- Layer 1: Counter(arr) counts · Layer 2: work on .values(), not keys
- Dict keys are unique by definition — checking keys always “passes” and misses the problem
- len(x) == len(set(x)) is the shortest duplicate check — faster than pairwise compares
Time O(n) one counting pass and one set build · Space O(n) for the Counter and the set of frequencies
Two-layer pattern: count first with Counter, then reason about the frequencies. And len(x) == len(set(x)) is the shortest way to ask “any duplicates?”