1 minute read

Problem Statement

leetcode problem link

My Solution [Accepted]

public class Solution {
    public bool UniqueOccurrences(int[] arr) {
        var counter = new Dictionary<int, int>();
        var seen = new HashSet<int>();
        foreach (var num in arr) {
            if (counter.ContainsKey(num))
                counter[num]++;
            else
                counter[num] = 1;
        }

        foreach (var val in counter.Values) {
            if (seen.Contains(val))
                return false;
            seen.Add(val);
        }

        return true;
    }
}

Editorial

Approach 1: Counting Sort

class Solution {
public:
    // Constant to make elements non-negative.
    static constexpr int K = 1000;

    bool uniqueOccurrences(vector<int>& arr) {
        vector<int> freq(2 * K  + 1);

        // Store the frequency of elements in the unordered map.
        for (int num : arr) {
            freq[num + K]++;
        }

        // Sort the frequency count.
        sort(freq.begin(), freq.end());

        // If the adjacent freq count is equal, then the freq count isn't unique.
        for (int i = 0; i < 2 * K; i++) {
            if (freq[i] && freq[i] == freq[i + 1]) {
                return false;
            }
        }

        // If all the elements are traversed, it implies frequency counts are unique.
        return true;
    }
};

Approach 2: HashMap & HashSet

class Solution {
public:
    bool uniqueOccurrences(vector<int>& arr) {
        // Store the frequency of elements in the unordered map.
        unordered_map<int, int> freq;
        for (int num : arr) {
            freq[num]++;
        }

        // Store the frequency count of elements in the unordered set.
        unordered_set<int> freqSet;
        for (auto [key, value] : freq) {
            freqSet.insert(value);
        }

        // If the set size is equal to the map size,
        // It implies frequency counts are unique.
        return freqSet.size() == freq.size();
    }
};