Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise.
?
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
From: LeetCode
Link: 1207. Unique Number of Occurrences
We can use a hash table (or an array, considering the constraints) to count occurrences. Then, we use another hash table to check for the uniqueness of these counts.
bool uniqueOccurrences(int* arr, int arrSize) {
int occurrences[2001] = {0}; // Array to count occurrences, offset by 1000 for negative numbers
bool seen[1001] = {false}; // Array to track if an occurrence count has been seen
// Count occurrences of each number
for (int i = 0; i < arrSize; i++) {
occurrences[arr[i] + 1000]++;
}
// Check for unique occurrences
for (int i = 0; i < 2001; i++) {
if (occurrences[i] > 0) {
if (seen[occurrences[i]]) {
// If we have already seen this count, it's not unique
return false;
}
seen[occurrences[i]] = true;
}
}
return true;
}