Unique Number of Occurrences
Problem
Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.
nums = [1, 2, 2, 1, 1, 3]truedef unique_occurrences(nums):
freq = {}
for x in nums:
freq[x] = freq.get(x, 0) + 1
seen = set()
for c in freq.values():
if c in seen:
return False
seen.add(c)
return True
function uniqueOccurrences(nums) {
const freq = new Map();
for (const x of nums) freq.set(x, (freq.get(x) || 0) + 1);
const seen = new Set();
for (const c of freq.values()) {
if (seen.has(c)) return false;
seen.add(c);
}
return true;
}
class Solution {
public boolean uniqueOccurrences(int[] nums) {
Map<Integer, Integer> freq = new HashMap<>();
for (int x : nums) freq.merge(x, 1, Integer::sum);
Set<Integer> seen = new HashSet<>();
for (int c : freq.values()) {
if (seen.contains(c)) return false;
seen.add(c);
}
return true;
}
}
bool uniqueOccurrences(vector<int>& nums) {
unordered_map<int, int> freq;
for (int x : nums) freq[x]++;
unordered_set<int> seen;
for (auto& p : freq) {
if (seen.count(p.second)) return false;
seen.insert(p.second);
}
return true;
}
Explanation
The question is really two questions stacked together: first, how often does each value appear? and second, are all of those counts different? We solve each part with a hash structure.
Step one builds a frequency map freq: walk the array and do freq[x] += 1 for every value x. Now freq holds each value paired with how many times it showed up.
Step two checks that the counts themselves are unique. We pour every count from freq.values() into a set called seen. If a count is already in the set, two different values shared the same frequency, so we return False right away. If we finish without a clash, we return True.
Example: nums = [1, 2, 2, 1, 1, 3]. The counts are 1→3, 2→2, 3→1. Feeding 3, 2, 1 into the set, none repeats, so the answer is true.
Both passes touch each item a constant number of times, so the whole check runs in linear time.