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.
1function uniqueOccurrences(arr) {
2 const countMap = new Map();
3 for (const num of arr) {
4 countMap.set(num, (countMap.get(num) || 0) + 1);
5 }
6 const occurrences = new Set(countMap.values());
7 return occurrences.size === countMap.size;
8}
9
10const arr = [1, 2, 2, 1, 1, 3];
11console.log(uniqueOccurrences(arr));
In this JavaScript solution, we use a Map to count how often each number appears and a Set to check for unique occurrence counts.
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.
1#include <iostream>
2#include <vector>
3#include <unordered_map>
4#include <algorithm>
5
6bool uniqueOccurrences(std::vector<int>& arr) {
7 std::unordered_map<int, int> countMap;
8 for (int num : arr) {
9 ++countMap[num];
10 }
11
12 std::vector<int> occurrenceList;
13 for (const auto& pair : countMap) {
14 occurrenceList.push_back(pair.second);
15 }
16
17 std::sort(occurrenceList.begin(), occurrenceList.end());
18
19 for (size_t i = 1; i < occurrenceList.size(); ++i) {
20 if (occurrenceList[i] == occurrenceList[i - 1]) {
21 return false;
22 }
23 }
24 return true;
25}
26
27int main() {
28 std::vector<int> arr = {1, 2, 2, 1, 1, 3};
29 std::cout << (uniqueOccurrences(arr) ? "true" : "false") << std::endl;
30 return 0;
31}
The C++ solution employs the sort function from the standard library to sort the occurrence counts after using an unordered_map to count them.