Unique Number of Occurrences

easy array hash map hash set

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.

Inputnums = [1, 2, 2, 1, 1, 3]
Outputtrue
Counts are 1→3, 2→2, 3→1, all distinct.

def 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;
}
Time: O(n) Space: O(n)