Unique Number of Occurrences (LeetCode 1207): Solution and Explanation
Given an integer array arr, count how often each distinct value appears. Return true when all of those counts are different from each other, and false when two values share the same count.
Intuition
The question has two layers. First you need the frequency of every value, and only then can you ask whether those frequencies repeat. Trying to answer both at once in a single scan gets messy, so split the work into two passes.
The first pass is a standard frequency count: a hash map from value to the number of times it appears. After it, the actual values no longer matter. Only the list of counts does.
The second pass is a duplicate check on that list of counts. Think of the counts as claiming slots labeled 1, 2, 3 and so on. A count that finds its slot already taken means two different values appear the same number of times, so the answer is false right away. If every count lands in an empty slot, the answer is true.
Approach: Count map plus a set of seen counts
- Build
count, a map from each value inarrto how many times it appears. - Create an empty set
seenfor counts that have already been claimed. - For each count
cin the map: ifcis already inseen, returnfalse. - Otherwise add
ctoseenand continue. - If the loop finishes, every count was different, so return
true.
Step-by-step example
arr = [1,2,2,1,1,3]
- Tally the array: 1 is seen at indices 0, 3 and 4, 2 at indices 1 and 2, and 3 at index 5.
- The count map is {1: 3, 2: 2, 3: 1}.
- Count 3 (for value 1) goes into the empty set: seen = {3}.
- Count 2 (for value 2) is not in the set, so seen = {3, 2}.
- Count 1 (for value 3) is not in the set either, so seen = {3, 2, 1}.
- Every count found a free slot, so the function returns true.
Code: Python, Java, C++
1class Solution:
2 def uniqueOccurrences(self, arr: List[int]) -> bool:
3 count = {}
4 for x in arr:
5 count[x] = count.get(x, 0) + 1
6 seen = set()
7 for c in count.values():
8 if c in seen:
9 return False
10 seen.add(c)
11 return True1class Solution {
2 public boolean uniqueOccurrences(int[] arr) {
3 Map<Integer, Integer> count = new HashMap<>();
4 for (int x : arr) {
5 count.merge(x, 1, Integer::sum);
6 }
7 Set<Integer> seen = new HashSet<>();
8 for (int c : count.values()) {
9 if (seen.contains(c)) {
10 return false;
11 }
12 seen.add(c);
13 }
14 return true;
15 }
16}1class Solution {
2public:
3 bool uniqueOccurrences(vector<int>& arr) {
4 unordered_map<int, int> count;
5 for (int x : arr) {
6 count[x]++;
7 }
8 unordered_set<int> seen;
9 for (auto& [x, c] : count) {
10 if (seen.count(c)) {
11 return false;
12 }
13 seen.insert(c);
14 }
15 return true;
16 }
17};Time and space complexity
O(n)
One pass over the array builds the map, and one pass over at most n distinct counts checks them. Each map and set operation is O(1) on average.
O(n)
The map holds one entry per distinct value and the set holds one entry per distinct count, each at most n.
Other approaches
Compare set sizes (time O(n), space O(n))
Build the count map, then compare the number of distinct values with the size of set(count.values()). They are equal exactly when no count repeats. It is shorter but always processes every count instead of stopping at the first clash.
Fixed-size arrays (time O(n + R), space O(R))
Values lie in [-1000, 1000], so an array of 2001 counters (offset by 1000) can replace the map, and a boolean array of length n + 1 can replace the set. This avoids hashing but is tied to the value range.
Sort and run-length (time O(n log n), space O(n))
Sort the array, measure the length of each run of equal values, then sort those run lengths and look for two equal neighbors. No hashing is needed, but the sorts cost extra time.
Common mistakes
- Checking whether values are unique instead of whether counts are unique. [1,2] has two different values but both appear once, so the answer is false.
- Building the set of counts while still counting. A count is only final after the whole array has been scanned, so the check belongs in a second pass.
- Forgetting negative values when using an array instead of a map. Indexing with a negative number either crashes or silently reads the wrong slot unless you add an offset.
- Treating a single distinct value as a special case. An array like [4,4,4,4] has one count, which is trivially unique, so the answer is true.
Frequently asked questions
Why does the order of the counts not matter?
The answer only asks whether any two counts are equal. Equality does not depend on order, so iterating the map in any order (hash order in Java or Go, insertion order in Python) gives the same result.
Can I stop as soon as I see a repeated count?
Yes. One repeated count is enough to make the answer false, so returning early is correct and saves the rest of the loop.
Is there an O(1) space solution?
Not in general. You must remember how often each value appeared, and there can be up to n distinct values. The fixed-size array version uses constant space only because the value range is bounded.
How is this related to Top K Frequent Elements?
Both start with the same frequency map. Top K Frequent then ranks the counts, while this problem only checks them for duplicates.