LeetCode #1207 Unique Number of Occurrences Solution & Explanation

LeetCode 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.


Solution

We can use a dictionary to store the number and it’s occurrences.

Subsequently, we employ a HashSet to check for any duplicate occurrences of numbers.

C# Solution

Solution1

public class Solution {
    public bool UniqueOccurrences(int[] arr) {
        Dictionary<int,int> dict =   new Dictionary<int,int>();

        //1.count number of occurrences of each value
        foreach(var a in arr)
        {
            if (!dict.ContainsKey(a))
            {
                dict.Add(a, 1);
            }
            else
            {
                dict[a] = dict[a]+1;
            }
        }

        //2.check if there any same number by HashSet
        HashSet<int> hSet = new HashSet<int>();
        foreach(var item in dict)
        {
            if(hSet.Contains(item.Value))
            {
                return false;
            }
            hSet.Add(item.Value);
        }

        return true;
    }
}

Java Solution

Solution1

class Solution {
    public boolean uniqueOccurrences(int[] arr) {
        Map<Integer, Integer> dict = new HashMap<Integer, Integer>();
        //1.count number of occurrences of each value
        for(int a : arr)
        {
            if (!dict.containsKey(a))
            {
                dict.put(a, 1);
            }
            else
            {
                dict.put(a, dict.get(a)+1);
            }
        }

        //2.check if there any same number by HashSet
        HashSet<Integer> hSet = new HashSet<Integer>();
        for(int val : dict.values()) 
        {
            if(hSet.contains(val))
            {
                return false;
            }
            hSet.add(val);
        }

        return true;
    }
}

Runtime : 2ms, 2ms, 2ms beats 98% Java submission


Conclusion

🧡If my solution helps, that is my honor!

🧡You can support me by sharing my posts, thanks a lot

If you got any problem about the explanation, please feel free to let me know

The problem link : Unique Number of Occurrences – LeetCode

See another similar problem using dictionary and hashset : LeetCode #290 Word Pattern Solution & Explanation

Some Random LeetCode posts

Leave a Reply

Your email address will not be published. Required fields are marked *