In this approach, we will first traverse the array to count the occurrences of each element using a hash map. Then, we will use a set to check if these occurrences are unique. If the size of the set matches the size of the occurrence counts, it implies all occurrences are unique.
Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(1), since we're using fixed-size arrays.
1import java.util.HashMap;
2import java.util.HashSet;
3
4public class UniqueOccurrences {
5 public static boolean uniqueOccurrences(int[] arr) {
6 HashMap<Integer, Integer> countMap = new HashMap<>();
7 for (int num : arr) {
8 countMap.put(num, countMap.getOrDefault(num, 0) + 1);
9 }
10 HashSet<Integer> occurrences = new HashSet<>();
11 for (int count : countMap.values()) {
12 if (!occurrences.add(count)) {
13 return false;
14 }
15 }
16 return true;
17 }
18
19 public static void main(String[] args) {
20 int[] arr = {1, 2, 2, 1, 1, 3};
21 System.out.println(uniqueOccurrences(arr));
22 }
23}
In the Java implementation, we use a HashMap to track element frequencies and a HashSet to ensure all frequencies are unique.
This alternative approach starts by counting occurrences just like the first one. After that, it stores these counts in a list, sorts the list, and then checks for any consecutive equal elements, which would indicate duplicate occurrences.
Time Complexity: O(n log n), due to sorting.
Space Complexity: O(1), since we work within fixed-sized arrays.
1def uniqueOccurrences(arr):
2 from collections import Counter
3 count = Counter(arr)
4 occurrences = sorted(count.values())
5 for i in range(1, len(occurrences)):
6 if occurrences[i] == occurrences[i - 1]:
7 return False
8 return True
9
10arr = [1, 2, 2, 1, 1, 3]
11print(uniqueOccurrences(arr))
The Python approach sorts the occurrence counts and checks for duplicates in a single pass of the sorted list.