Unique Number of Occurrences
Given an array of integers, return true if the number of occurrences of each value in the array is unique. Return false otherwise.
First, count the frequency of each value using a hash map. Then, check if all the frequencies are unique by putting them into a hash set. If the size of the hash set equals the number of distinct values in the hash map, all frequencies are unique.
For example, arr = [1,2,2,1,1,3] has frequencies: 1 appears 3 times, 2 appears 2 times, 3 appears 1 time. All frequencies (3, 2, 1) are unique. Return true.
This problem tests understanding of both hash maps (for counting frequencies) and hash sets (for checking uniqueness). It combines two hash-based data structures in one problem.
The problem has two clear phases: counting frequencies and checking for uniqueness. The hash map handles frequency counting in O(n) time. The hash set then checks if any two values in the hash map have the same count by trying to insert each count into the set. If a count already exists in the set, the frequencies are not unique.
An empty array returns true because there are zero frequencies, which trivially means all frequencies are unique. Arrays with a single element also return true.
Example Input & Output
Freq: 1->3, 2->2, 3->1. All unique.
Freq: 1->1, 2->2, 3->3. All unique.
Freq: 1->1, 2->1. Both 1, not unique.
Algorithm Flow

Solution Approach
Count frequencies with hash map. Store counts in a hash set. Return size of set == size of map.
Time O(n), Space O(n).
Best Answers
import java.util.*;
class Solution {
public boolean solution(int[] arr) {
Map<Integer,Integer> freq = new HashMap<>();
for (int x : arr) freq.put(x, freq.getOrDefault(x, 0) + 1);
Set<Integer> uniq = new HashSet<>(freq.values());
return uniq.size() == freq.size();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
