class Solution:
def uniqueOccurrences(self, arr):
from collections import Counter
freq = Counter(arr)
occurrences = list(freq.values())
return len(set(occurrences)) == len(occurrences)
class Solution {
public:
bool uniqueOccurrences(vector<int>& arr) {
unordered_map<int, int> freq;
for (int num : arr) {
freq[num]++;
}
unordered_set<int> occ;
for (auto &p : freq) {
if (!occ.insert(p.second).second) {
return false;
}
}
return true;
}
};
class Solution {
public boolean uniqueOccurrences(int[] arr) {
Map<Integer, Integer> freq = new HashMap<>();
for (int num : arr) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
}
Set<Integer> occ = new HashSet<>();
for (int count : freq.values()) {
if (!occ.add(count)) {
return false;
}
}
return true;
}
}
var uniqueOccurrences = function(arr) {
const freq = {};
for (const num of arr) {
freq[num] = (freq[num] || 0) + 1;
}
const occurrences = Object.values(freq);
return new Set(occurrences).size === occurrences.length;
};
Given an array of integers arr
, determine if the number of times each value occurs is unique. In other words, return true
if and only if no two distinct values in arr
have the same number of occurrences.
arr
.true
if the counts are unique; otherwise, return false
.arr
has at least one element and all elements are integers.The problem asks us to check if the frequencies of elements in an array are all different. A naive way would be to compare every frequency with every other one, but that would be inefficient. Instead, we can leverage data structures that help us count and check uniqueness efficiently.
This approach is more efficient than brute-force comparison, as it avoids redundant checks and leverages fast lookups.
Let's break down the solution step by step:
true
if all frequencies are unique, else false
.We use hash maps and sets because their typical operations (insert, lookup) are O(1) on average, making the solution efficient.
Let's consider arr = [1,2,2,1,1,3]
.
true
Now, consider arr = [1,2,2,1,1,3,3,3]
:
false
arr
.The use of hash maps and sets makes the solution efficient even for large arrays.
The Unique Number of Occurrences problem can be efficiently solved by counting how often each number appears and then checking if all these counts are unique. By using hash maps for counting and sets for uniqueness checking, we avoid inefficient brute-force comparisons and ensure our solution runs in linear time. This approach is both concise and elegant, leveraging fundamental data structures for clarity and efficiency.