Tuesday, February 27, 2024

[LeetCode] Unique Number of Occurrences

Problem: Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise.

Example:

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


Approach: We can use sorting to solve this problem but it will take nlogn time. To solve it in less time we can use a Map and a Set. First in the Map we will store the frequency of each element in the array and then we will traverse the Map and see if there are any repeated values in it using the Set.

That's all!


Implementation in C#:

    public bool UniqueOccurrences(int[] arr)
    {
        int length = arr?.Length ?? 0;
        if (length <= 1)
        {
            return true;
        }
        Dictionary<int, int> freqMap = new Dictionary<int, int>();
        foreach (int num in arr)
        {
            if (!freqMap.ContainsKey(num))
            {
                freqMap[num] = 0;
            }
            ++freqMap[num];
        }
        HashSet<int> freqSet = new HashSet<int>();
        foreach (int key in freqMap.Keys)
        {
            if (!freqSet.Add(freqMap[key]))
            {
                return false;
            }
        }
        return true;
    }

Complexity: O(n)

No comments:

Post a Comment