Algorithm
Problem Name: 1207. Unique Number of Occurrences
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 <= arr.length <= 1000
-1000 <= arr[i] <= 1000
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
public boolean uniqueOccurrences(int[] arr) {
Map map = new HashMap<>();
for (int num : arr) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
return map.size() == new HashSet < >(map.values()).size();
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const uniqueOccurrences = function(arr) {
const hash = {}
for(let e of arr) {
if(hash[e] == null) hash[e] = 0
hash[e]++
}
const ks = new Set(Object.keys(hash)), vs = new Set(Object.values(hash))
return ks.size === vs.size
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
from collections import Counter as cnt
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
return all(v == 1 for v in cnt(cnt(arr).values()).values())
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with C# Programming
Code -
C# Programming
using System.Collections.Generic;
namespace LeetCode
{
public class _1207_UniqueNumberOfOccurrences
{
public bool UniqueOccurrences(int[] arr)
{
var map = new Dictionary < int, int>();
foreach (var num in arr)
{
if (map.ContainsKey(num))
map[num]++;
else
map[num] = 1;
}
var set = new HashSet < int>();
foreach (var value in map.Values)
set.Add(value);
return set.Count == map.Count;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output