Unique Number of Occurrences

LeetCode Question 1207

Krishna Shrivastava
36 views
LinkedInGithubX
0
0
Unique Number of Occurrences
Listen to articleAudio version
Ad
Advertisement

LeetCode Problem 1207

Link of the Problem to try -: Link


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 1:

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.

Example 2:

Input: arr = [1,2]
Output: false

Example 3:

Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
Output: true


Constraints:

  1. 1 <= arr.length <= 1000
  2. -1000 <= arr[i] <= 1000


Solution:

It is a little bit tricky question as it says you have to return true if the elements frequency contained by the array is distinct and no frequency is same if it is then return true otherwise false. So for solving this we can use HashMap to make frequency of each element then we will create a Set and store all the values of HashMap elements in the Set and then we will simply compare sizes of both Map and Set as we know that if each element frequency is unique then the sizes are same otherwise size are not same and that is a key point to solve this question very easily.


Code:

HashMap<Integer,Integer> mp = new HashMap<>();
Set<Integer> ms = new HashSet<>();
for(int i=0;i<arr.length;i++){
mp.put(arr[i],mp.getOrDefault(arr[i],0)+1);
}
for(int u:mp.values()){
ms.add(u);
}
if(ms.size() == mp.size()){
return true;
}else{
return false;
}
Ai Assistant Kas